PHP PDO语法错误或访问冲突:1064

时间:2013-07-29 22:22:26

标签: php mysql pdo

遇到了我似乎没有看到的问题。

这是我的功能

function addIT($type, $amount, $id) {
$db = new database();
$conn8 = $db->connect();
$addit = $conn8->prepare("UPDATE accountTable SET :type = :type + :amount WHERE ID =     :id");
$addit->execute(array('type'=>$type, 'amount'=>$amount, 'id'=>$id));
}
接下来是我的电话:

$type = "age";
$amount = 17;
$id = 1;
addIT($type, $amount, $id);

现在执行代码时它会给我以下错误

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 ''age' = 'age' + '17' WHERE ID = '1'' at line 1' in /Library/WebServer/Documents/me/functions/activity.php:7 Stack trace: #0 /Library/WebServer/Documents/me/functions/activity.php(7): PDOStatement->execute(Array) #1 /Library/WebServer/Documents/me/content/doadd.php(66): addIT('age', 17, '1') #2 /Library/WebServer/Documents/me/main(48): include('/Library/WebSer...') #3 /Library/WebServer/Documents/me/where.php(25): include('/Library/WebSer...') #4 {main} thrown in /Library/WebServer/Documents/me/functions/activity.php on line 7

我确定我的执行或准备声明中有错误。我再也看不到了。

2 个答案:

答案 0 :(得分:4)

您的查询中不能包含变量列或表名。使用

UPDATE accountTable 
SET age = age + :amount 
WHERE ID = :id
顺便说一下,你不应该存储一个人的年龄,而应该存在生日。然后你不必更新它。

答案 1 :(得分:2)

function addIT($conn, $type, $amount, $id)
{
    $allowed = array('age','sex','whatever');
    if (!in_array($type,$allowed))
    {
         throw new Exception("Invalid type");
    }
    $sql = "UPDATE accountTable SET `$type` = `$type` + :amount WHERE ID = :id"
    $stm = $conn->prepare($sql);
    $stm->execute(array('amount'=>$amount, 'id'=>$id));
}