PDO prepare with question marks doesn't work with numbers [duplicate]

时光怂恿深爱的人放手 提交于 2020-04-11 17:11:33

问题


I have this :

$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');

$max = 10;
$min = 0;
$q = $_GET['q'];

$result = $pdo->prepare("SELECT * FROM fruits WHERE name LIKE ? LIMIT ?, ?");
$result->execute(array('%'.$q.'%', $min, $max));

However it doesn't work (returns nothing) while when I replace LIMIT by LIMIT 0, 10 and remove $min and $max from the array it works. What am I doing wrong? I tried using '0' instead of 0 but it doesn't work either...


回答1:


PDO::execute escapes all params as STRING.

$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');

$max = 10;
$min = 0;
$q = (isset($_GET['q']) && is_string($_GET['q'])) ? $_GET['q'] : '';

$stmt = $pdo->prepare('SELECT * FROM fruits WHERE name LIKE ? LIMIT ?, ?');
$stmt->bindValue(1, "%{$q}%", PDO::PARAM_STR);
$stmt->bindValue(2, $min    , PDO::PARAM_INT);
$stmt->bindValue(3, $max    , PDO::PARAM_INT);
$stmt->execute();



回答2:


My guess is that the numbers are being binded as strings. From the manual:

An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as PDO::PARAM_STR.

So you should use bindValue instead of the execute shortcut.



来源:https://stackoverflow.com/questions/16498640/pdo-prepare-with-question-marks-doesnt-work-with-numbers

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