2

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?

1 Answer 1

3

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();
Sign up to request clarification or add additional context in comments.

1 Comment

So that was the error I have been making. I needed three "s" because there are three strings. Thank you so much. Will accept answer ASAP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.