mysql动态插入

时间:2015-12-23 11:43:23

标签: mysql sql

在sql命令中:

INSERT INTO table(id,name) VALUES('&id','&name');

动态读取idname的值并插入表格 我试图在MySql中实现此查询,但我收到了错误 在MySql中实施此查询的正确方法是什么?

1 个答案:

答案 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();
}

?>

希望这有助于您使用插入语句。