在PHP中,我想执行一个SQL查询,它将数组值与SQL语句一起传递。我无法做到这一点。
请考虑以下
$db = "mydatabase.sqlite";
$array = array(
"key1" => "value1",
"key2" => "value2",
"key3" => "value3"
);
try {
$dbhandle = new PDO("sqlite:$db");
$dbhandle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
foreach ($array as $item) {
$timestamp =
$dbhandle->exec(
"INSERT OR REPLACE INTO table (field1, field2, field3)
VALUES ('$item['key1']', '$item['key2']', '$item['key3']')"
);
$dbhandle = NULL;
}
}
catch(PDOException $e) {
print "Exception : ".$e->getMessage()."\n";
}
如何表达SQL语句?
答案 0 :(得分:1)
将数组元素插入字符串时,请勿在键周围加上引号:
"INSERT OR REPLACE INTO table (field1, field2, field3)
VALUES ('$item[key1]', '$item[key2]', '$item[key3]')"
或使用花括号的“复杂”语法:
"INSERT OR REPLACE INTO table (field1, field2, field3)
VALUES ('{$item['key1']}', '{$item['key2']}', '{$item['key3']}')"
但是,最好使用预先准备好的声明:
$stmt = $dbhandle->prepare("INSERT OR REPLACE INTO table (field1, field2, field3)
VALUES (:key1, :key2, :key3)");
$stmt->execute($item);