2

遇到一个我似乎看不到的问题。

这是我的功能

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

我确定我的执行或准备语句有问题。我不再看到它了。

4

2 回答 2

4

您的查询中不能有可变的列名或表名。采用

UPDATE accountTable 
SET age = age + :amount 
WHERE ID = :id

顺便说一句,您不应该存储一个人的年龄,而是存储生日。那么你不必更新它。

于 2013-07-29T22:24:40.787 回答
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));
}
于 2013-07-29T22:29:01.673 回答