0

我正在学习 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'];

任何帮助,将不胜感激!

4

1 回答 1

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

于 2013-08-05T02:35:19.433 回答