Reputation: 535
In sql command:
INSERT INTO table(id,name) VALUES('&id','&name');
Reads the values of id
, name
dynamically and inserts into the table.
I was trying to implement this query in MySql
but I got error.
What is the right way to implement this query in MySql
?
Upvotes: 0
Views: 3635
Reputation: 37099
If you are inserting data into MySQL through command line or a tool like Workbench or HeidiSQL, just use:
INSERT INTO table(id,name) VALUES('some-string','some-string');
If you are entering data through PHP, it is advisable to use PDO and bound parameters like so:
<?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();
}
?>
Hopefully this will help you get going with your insert statements.
Upvotes: 2