在sql命令中:
INSERT INTO table(id,name) VALUES('&id','&name');
动态读取id
,name
的值并插入表格
我试图在MySql
中实现此查询,但我收到了错误
在MySql
中实施此查询的正确方法是什么?
答案 0 :(得分:2)
如果您通过命令行或Workbench或HeidiSQL等工具将数据插入MySQL,请使用:
INSERT INTO table(id,name) VALUES('some-string','some-string');
如果您通过PHP输入数据,建议使用PDO和绑定参数,如下所示:
<?php
$db = new PDO('mysql:host=localhost;dbname=test', 'test', 'test');
$sql = 'insert into table(id, name) values (:id, :name)';
// Notice that we aren't giving any values yet.
// We are just putting placeholders called :id and :name in the query
$statement = $db->prepare($sql);
if ($statement === false) {
echo 'statement didnt work';
exit();
}
// get your data from somewhere
$id = 12;
$name = 'guru';
try {
$result = $statement->execute(array(':id'=>$id, ':name'=>$name));
// in the above statement, we execute the statement
// during execution we provide a valid id and name to the
// placeholders :id and :name, respectively
if ($result === false) {
$error = $statement->errorInfo();
print_r($error);
}
else {
print_r($result);
echo 'Inserted', "\n";
}
}
catch (PDOException $e) {
echo $e->getMessage();
}
?>
希望这有助于您使用插入语句。