PDO参数和查询中的变量

时间:2014-10-02 23:16:59

标签: php

我有多个if和elseif语句,如下所示:

if ($str == "CARS") {
    $first = $db->prepare('INSERT INTO table_CAR (id_CAR, anything) VALUES (:id_CAR, :anything) ON DUPLICATE KEY UPDATE id_CAR = LAST_INSERT_ID(id_CAR)');
    $first->bindParam(':id_CAR', $null = null, PDO::PARAM_NULL);
    $first->bindParam(':anything', $anything, PDO::PARAM_STR);
    $first->execute();
}
else if ($str == "PLANES") {
    $first = $db->prepare('INSERT INTO table_PLANES (id_PLANES, anything) VALUES (:id_PLANES, :anything) ON DUPLICATE KEY UPDATE id_PLANES = LAST_INSERT_ID(id_PLANES)');
    $first->bindParam(':id_PLANES', $null = null, PDO::PARAM_NULL);
    $first->bindParam(':anything', $anything, PDO::PARAM_STR);
    $first->execute();
}

现在我想做一个功能,因为也有同样的事情。唯一的区别是名字。但是我怎样才能把这些词(CAR和PLANES)变成变量呢?我的问题是,这些单词是查询和参数的一部分,它们并不总是相同的(CARS!= CAR)。

1 个答案:

答案 0 :(得分:0)

您始终可以首先在变量中构造sql查询:

function insert($table, $anything) {
    // check $table using a whitelist to prevent SQL injections!
    $sql = 'INSERT INTO table_' . $table . ' (anything) VALUES (:anything)';

    $first->bindParam(':anything', $anything, PDO::PARAM_STR);
    $first->execute();
}

如您所见,我稍微清理了您的查询。由于MySQL将为您插入正确的值,因此无需为AUTO_INCREMENT字段插入NULL值。