Reputation: 1191
I am trying to insert data in a database using MYSQLi. If I use the following query, data is inserted;
INSERT INTO table (Name, Phone, Location) VALUES ('test', 'test', 'test')
Instead of the value 'test', I need the value of a variable inserted. However the following does not work.
$test = 'xxx';
if ($stmt = $mysqli->prepare("INSERT INTO table (Name, Phone, Location) VALUES (".$test.", 'aaa', 'bbb')")) {
$stmt->execute();
$stmt->close();
}
I have tried the bind_param
command, but it didn't work.
$stmt->bind_param("ss", $name, $phone, $location);
How can I insert a variable directly?
Upvotes: 2
Views: 4257
Reputation: 24276
In your case the code should be like this:
$test = 'xxx';
$stmt = $mysqli->prepare("INSERT INTO table (Name, Phone, Location) VALUES (?, 'aaa', 'bbb')");
$stmt->bind_param("s", $test);
$stmt->execute();
$stmt->close();
If you want to have 3 variables for this query:
$name = "My name";
$phone = "My phone number";
$location = "My location";
$stmt = $mysqli->prepare("INSERT INTO table (Name, Phone, Location) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $phone, $location);
$stmt->execute();
$stmt->close();
Upvotes: 3