带参数的PHP MySQL查询返回sytax错误,因为参数
我有以下php代码:带参数的PHP MySQL查询返回sytax错误,因为参数,php,mysql,Php,Mysql,我有以下php代码: $id=1; $query = 'select id from role_perm where perm_id = :id'; if($statement =$GLOBALS["DB"]->prepare($query)){ $result =& $statement->execute(array(':id' => $id)); $t = $result->fetch_all(); 但当我尝试运行此代码时,我
$id=1;
$query = 'select id from role_perm where perm_id = :id';
if($statement =$GLOBALS["DB"]->prepare($query)){
$result =& $statement->execute(array(':id' => $id));
$t = $result->fetch_all();
但当我尝试运行此代码时,我得到一个错误:
1064您的SQL语法有错误;检查手册
对应于您的MySQL服务器版本,以便使用正确的语法
第1行的“:id”附近
我在网上查阅了很多问题和信息,试图用不同的方式表达我的观点,但我总是以这样的错误告终,我试过了吗?对于参数也是如此。如何使其识别参数?
我的数据库配置:
$databaseConnection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($databaseConnection->connect_error)
{
die("Database selection failed: " . $databaseConnection->connect_error);
}
// Create tables if needed.
prep_DB_content();
$GLOBALS['DB'] = $databaseConnection ;
什么是
$GLOBALS[“DB”]
?换句话说,您使用什么数据库驱动程序?我猜您正在尝试将PDO
语法与mysql
或mysqli
驱动程序一起使用。请查看示例2(如果您使用的是PDO)中的PDO文档页面--@arkascha ok i updated。我正在使用mysqli,你是对的!那么我应该更改什么?我建议您查看一下文档:查询结果是否只有一个?如果是这样,我将更改我的应答addecho$statement->num\u行代码>执行后();然后告诉我它说了什么。我记得你需要把$statement->store_result()
在num_行之前,如果放入echo$id_结果,请再次尝试代码>在while循环中是否仍返回错误?是,这是正确的,但不是针对bind_结果,而是针对bind_参数。查询中的每个输入变量都需要一个字母作为示例:$statement->bind_param(“ss”、$string1、$string2)代码>如果查询中有两个需要字符串的问号。
$query = 'select id from role_perm where perm_id = ?';
if($statement = $GLOBALS["DB"]->prepare($query)){
$statement->bind_param("i", $id);
$statement->execute();
$statement->store_result();
$statement->bind_result($id_result);
while ($statement->fetch()) {
// code here
}
$statement->close();
}