动态查询和PDO bindParam

时间:2018-06-05 10:16:25

标签: php mysql sql pdo

我有一个动态查询,具体取决于网址上的参数,出于某种原因,当我在网址中有scooter_id时,它会返回空值。

我从未尝试过使用动态绑定参数,但我可能会遇到错误,但如果我从网址中删除scooter_id,则会返回所有以洛杉矶为位置的滑板车。问题是当我在网址中有scooter_id时。

这是我的代码

url示例:http://domain/json.php?auth=R4g6@iPn[,TyUN&location=Los%20Angeles&scooter_id=ID00002

<?php

include_once("dbconfig.php");

$location=$_GET['location'];
$auth=$_GET['auth'];
$scooter_id=$_GET['scooter_id'];

$param=array();

if($auth!='R4g6@iPn[,TyUN')
{
    $data[] = array(
                "error" => 'Authentification failed',

                );

                echo json_encode ( $data);
}
else
{
if($location!='')
{
    $sql="SELECT * FROM coordonate where location=:location";
    $param=array(
            'location' => $location
            )
        if ($scooter_id!='')
        {
            $sql .='and id_scooter=:scooter_id';
            $param['scooter_id']=$scooter_id;

        }

                                $stmt=$dbh->prepare($sql);
                                foreach($param as $key => $value)
                                {
                                    $stmt->bindParam(':'.$key.'',$value);
                                }
                                $stmt->execute();
                                while ($row=$stmt->fetch())
                                {


                $data[] = array(
                "scooter_id" => ''.$row['id_scooter'].'',
                "title" => "BOOSTER PLUS S",
                "location" => ''.$row['location'].'',
                "lat" => ''.$row['lat'].'',
                "longi"  => ''.$row['longi'].'',
                "alt" => ''.$row['alt'].'',
                "speed" => ''.$row['speed'].'',
                "ip" => ''.$row['ip'].'',
                "port" => ''.$row['port'].'',
                "nr_satelites" => ''.$row['nr_satelites'].'',
                "status" => ''.$row['status'].''

                );
                                }


// Encoding array in JSON format
echo json_encode ( $data);
}
else
{
    $data[] = array(
                "error" => 'Location is mandatory',

                );

                echo json_encode ( $data);
}
}
?>

0 个答案:

没有答案