Bindparam中的PHP MySQL PDO语法错误

时间:2015-04-10 12:32:12

标签: php mysql pdo

您好我正在尝试使用PHP

使用MySQL PDO从表中选择一些随机行
$query = $conn->prepare("SELECT * FROM `products` WHERE `cat` = :cat ORDER BY RAND() LIMIT :limit_to");

$query->bindParam(':limit_to', $limit, PDO::PARAM_INT);
$query->bindParam(':cat', $cat, PDO::PARAM_INT);
$stmt = $query->execute();

但是这会引发像这样的mysql语法错误,

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''2'' at line 1"

导致此错误的原因是什么?为什么?

中我没有看到任何错误

1 个答案:

答案 0 :(得分:3)

问题是当你执行$limit = $_REQUEST['limit'];时,变量$ limit的类型为string

例如(两者都包含数字,但变量类型不同):

$varInt = 2;
$varString = "2";

var_dump ($varInt);
var_dump ($varString);

prints:
    int 2
    string '2' (length=1)

因此,您准备好的陈述将与以下内容绑定:

$limit = $_REQUEST['limit']; // $_REQUEST['limit'] = 2
$cat = 3;

SELECT * FROM `products` WHERE `cat` = :cat ORDER BY RAND() LIMIT :limit_to

绑定:limit_to =' 2',:cat =' 3'

问题在于LIMIT语法。符号''打破了语法。您必须确保将整数变量绑定到$ limit。

// do it in first place you have access to $_REQUEST['limit'] or other global arrays , for example $_GET, $_POST

$limit = intval($_REQUEST['limit']); // $_REQUEST['limit'] = 2
 $cat = intval($blablabla); // or from any other source

$query = $conn->prepare("SELECT * FROM products WHERE 
                         cat = :cat ORDER BY RAND() 
                                    LIMIT :limit_to");

$query->bindValue(':limit_to', $limit, PDO::PARAM_INT);
$query->bindValue(':cat', $cat, PDO::PARAM_INT);
$stmt = $query->execute();

P.S 使用bindValue(),在99%的情况下效果更好。