PHP PDO抛出致命错误1064

时间:2013-08-05 02:28:44

标签: php prepared-statement

我正在学习PDO和准备好的语句并遇到了问题。我一直收到这个错误:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error
or access violation: 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 ''Users' WHERE
Username = 'yayu'' at line 1' in /home/u230594705/public_html/pages/panel.php:33 Stack
trace:#0 /home/u230594705/public_html/pages/panel.php(33): PDOStatement->execute(Array) #1 
{main} thrown in /home/u230594705/public_html/pages/panel.php on line 33

使用此代码:

session_start();

$user = $_SESSION["user"];
$table = "Users";

//Establish Connection
$dsn = "mysql:host=$dbHost;dbname=$dbName;charset=utf8";
$opt = array(
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        );
$pdo = new PDO($dsn,$dbUser,$dbPass, $opt);

//Prepare query to execute
$stmt = $pdo->prepare("SELECT Username, Password, Email FROM ? WHERE Username = ?");

$stmt->execute(array($table, $user));
$row = $stmt->fetch();

//Check
echo $row['Username'];

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您无法为表名和列名指定参数。

更改您的$stmt,如下所示:

$stmt = $pdo->prepare("SELECT Username, Password, Email FROM $table WHERE Username = ?");

您的execute如下:

$stmt->execute(array($user));

这是一个很好的解释,为什么你不能为表名或列名指定参数: http://www.php.net/manual/en/pdo.prepare.php#111977