acc1999
acc1999

Reputation: 25

Confused about PHP syntax for inserting variables in SQL query

$firstName = mysqli_real_escape_string($dbcon, $_POST['newFirstName']);
$lastName = mysqli_real_escape_string($dbcon, $_POST['newLastName']);
$emailAddress = mysqli_real_escape_string($dbcon, $_POST['newEmailAddress']);

$sqlQuery = "INSERT INTO admins (firstname, lastname, email) VALUES ('$firstName','$lastName','$emailAddress')
  ON DUPLICATE KEY UPDATE firstname ='".$firstName."' lastname='".$lastName."' email='".$emailAddress."'";

My issue is on the last line. AFAIK you have to use double quotes for PHP to actually insert your variable into the string, but no matter what quotes I use I get errors. What's the proper syntax for inserting the variables?

Upvotes: 1

Views: 43

Answers (2)

Leander Iversen
Leander Iversen

Reputation: 83

You should separate the columns you're updating with a comma. e.g:

ON DUPLICATE KEY UPDATE firstname ='".$firstName."', lastname='".$lastName."', 
email='".$emailAddress."'";

Upvotes: 1

DKyleo
DKyleo

Reputation: 826

You are missing commas from your SQL query in between the parameters you are updating.

Additionally for your update statement, you need to specify the table and SET:

"Update admins
Set firstname = '". $firstname . "' , lastname = '" . $lastname . "' " etc.

Upvotes: 1

Related Questions