问题描述
这是我遇到的错误...
Here's the error I'm getting...
Failed to prepare statement: (1064) 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 '?.Pages WHERE slug='?'' at line 1
这是我的代码...
require_once("../database/config.php");
$pageSlug = "home";
$db = new mysqli(_DB_HOST, _DB_USER, _DB_PASSWORD, _DB_NAME);
if ( $db->connect_errno ) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
exit();
}
if ( !$selectQuery = $db->prepare("SELECT * FROM ?.Pages WHERE slug='?'") ) {
echo "Failed to prepare statement: (" . $db->errno . ") " . $db->error;
exit();
}
if ( !$selectQuery->bind_param("ss", _DB_NAME, $pageSlug) ) {
echo "Binding parameters failed: (" . $selectQuery->errno . ") " . $selectQuery->error;
exit();
}
if ( !$selectQuery->execute() ) {
echo "Exexute failed: (" . $selectQuery->errno . ") " . $selectQuery->error;
exit();
}
echo "<pre>I GOT HERE!</pre>";
exit();
../database/config.php
仅包含我上面引用的全局变量("_DB_NAME"等).
The ../database/config.php
just contains the global variables that I reference above ("_DB_NAME", etc).
我想我仍然只是把头放在准备好的声明周围,而我真的不知道我在做什么错.
I guess I'm still just wrapping my head around this prepared statements things and don't really know what I'm doing wrong.
提前谢谢!
推荐答案
准备好的语句不能使用参数来提供标识符(模式名称,表名称,列名称等),因为在提交之前,它们已提交给DBMS以验证语法提供这些参数的值.
Prepared statements can not use parameters to supply identifiers (schema names, table names, column names, etc), because they are submitted to DBMS to verify syntax, before supplying values of those parameters.
http://dev.mysql.com/doc/refman/5.0/en/prepare.html
仍然,您可以使用动态SQL.示例:
Still, you may use dynamic SQL. Example:
$table = 'Example'; // Should be safe, avoid user input.
$sql = "SELECT * FROM `{$table}` WHERE `id` = ?";
$stmt = $db->prepare($sql);
// ...
UPD:
我注意到,您在字符串参数标记周围使用了单引号'
.应该避免使用它们,因为dbms会自己关心它们. slug='?'
应该是slug = ?
.
I've noticed, that you're using single quotes '
around string parameter markers. They are should be avoided because, dbms cares about them by itself. slug='?'
should be slug = ?
.
请仔细阅读: http://php.net/mysqli-prepare .
这篇关于试图学习mysqli准备好的语句;我究竟做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!