Php PDO sql statement with single quotes

ε祈祈猫儿з 提交于 2021-01-28 10:04:59

问题


I have a mysql php pdo statement that has single quotes to call the Mysql Geolocation "POINT" function as such.

    $sql = "INSERT INTO userTrip 
        (userId, fromLat, fromLon, fromLoc, fromPOI,
        toLat, toLon, toLoc, toPOI,
        tripFinished, isMatched, departureTime, createdAt)
        values 
        (:user,:fromLat,:fromLon, GeomFromText('POINT(:fromLat1 :fromLon1)'),:fromPOI,:toLat,
        :toLon, GeomFromText('POINT(:toLat1 :toLon1)'),:toPOI,0,0,:departureTime,:date)";

    $stmt = $db->prepare($sql);        

    $stmt->bindParam(':user', $userId, PDO::PARAM_INT);
    $stmt->bindParam(':fromLat', $fromLat, PDO::PARAM_STR);
    $stmt->bindParam(':fromLon', $fromLon, PDO::PARAM_STR);
    $stmt->bindParam(":fromLat1", $fromLat, PDO::PARAM_STR);
    $stmt->bindParam(':fromLon1', $fromLon, PDO::PARAM_STR);
    $stmt->bindParam(':fromPOI', $fromPOI, PDO::PARAM_STR);
    $stmt->bindParam(':toLat', $toLat, PDO::PARAM_STR);
    $stmt->bindParam(':toLon', $toLon, PDO::PARAM_STR);        
    $stmt->bindParam(':toLat1', $toLat, PDO::PARAM_STR);        
    $stmt->bindParam(':toLon1', $toLon, PDO::PARAM_STR); 
    $stmt->bindParam(':toPOI', $toPOI, PDO::PARAM_STR);
    $stmt->bindParam(':departureTime', $departureTime, PDO::PARAM_STR);
    $stmt->bindParam(':date', date('Y-m-d H:i:s'), PDO::PARAM_STR);

when I execute the query it throws an exception "PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens" even though the number of parameters are correct. I suspect the single quotes throw off the query but I need to put them in. I tried escaping them using backslash and everything else I could think of but the query wont execute. Is there a way around this?


回答1:


You don't need quotes. You need to pass a parameter into function. That's what prepared statements are for.

define a value first

$point = "POINT($fromLat $fromLon)";

then prepare your query usual way

..., GeomFromText(:point), ...

then bind this $point variable to :point placeholder.




回答2:


If you need to embed a single quote in the SQL string, this

(:user,:fromLat,:fromLon, GeomFromText('POINT(:fromLat1 :fromLon1)'),:fromPOI,:toLat,

might need to be this.

(:user,:fromLat,:fromLon, GeomFromText(''POINT(:fromLat1 :fromLon1)''),:fromPOI,:toLat,
-- Two single quotes                   ^^                          ^^ 


来源:https://stackoverflow.com/questions/15732948/php-pdo-sql-statement-with-single-quotes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!