简体   繁体   中英

PHP PDO SQL error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number

I can't see what is wrong in this sql. The simpliest sql without Haversine formula works perfect. So I mean should be something aboutthe sql or statments. I can't see it. Some idea? Thanks,

<?php
require_once "connectPDO.php";

// Get parameters from URL
$lat = 55; //$_GET["lat"];
$lng = 3; //$_GET["lng"];
$radius = 18; //$_GET["radius"];

// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);

//$query = $db->prepare("SELECT id, coursename, lat, lng FROM wp_courses");
$query = $db->prepare("SELECT coursename, lat, lng, 
( 3959 * acos( cos( radians(:latitude) ) * cos( radians( lat ) ) 
* cos( radians( lng ) - radians(:longitude) ) + sin( radians(:latitude) )
* sin( radians( lat ) ) ) ) AS distance FROM wp_courses
HAVING distance < :radius ORDER BY distance LIMIT 0 , 20");
$query->bindParam(':latitude', $lat, PDO::PARAM_STR);
$query->bindParam(':longitude', $lng, PDO::PARAM_STR);
$query->bindParam(':radius', $radius, PDO::PARAM_STR);
$query->execute();

header("Content-type: text/xml");
foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $node = $dom->createElement("marker");
    $newnode = $parnode->appendChild($node);
    $newnode->setAttribute("name", $row['coursename']);
    $newnode->setAttribute("lat", $row['lat']);
    $newnode->setAttribute("lng", $row['lng']);
    $newnode->setAttribute("distance", $row['distance']);
}
echo $dom->saveXML();
?>

You cannot reuse the same parameter name in your query, but it is simple to just change them a little like this

$query = $db->prepare("SELECT coursename, lat, lng, 
( 3959 * acos( cos( radians(:latitude1) ) * cos( radians( lat ) ) 
* cos( radians( lng ) - radians(:longitude) ) + sin( radians(:latitude2) )
* sin( radians( lat ) ) ) ) AS distance 
FROM wp_courses
HAVING distance < :radius ORDER BY distance LIMIT 0 , 20");

$query->bindParam(':latitude1', $lat, PDO::PARAM_STR);
$query->bindParam(':latitude2', $lat, PDO::PARAM_STR);
$query->bindParam(':longitude', $lng, PDO::PARAM_STR);
$query->bindParam(':radius', $radius, PDO::PARAM_STR);
$query->execute();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM