What is the error in this sprintf ()?

0
$sql = sprintf("INSERT INTO users (firstname, lastname, email, phone, state, dob, rules, pepsico_news) VALUES (%s, %s, %s, %s, %s, %s, %u, %s)", $fname, $lname, $email, $phone, $state, $dob, $rules, $pepsico_news);
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near '@gmail.com, 55555555555, NY, 01.10.89, 0, no)' at line 1

I have tried to find the error but I can not find it, sure it is some syntax but I can not find it.

    
asked by Santiago D'Antuoni 25.04.2017 в 18:22
source

1 answer

1

You could try this way:

<?php

$sql = sprintf("INSERT INTO users (firstname, lastname, email, phone, state, dob, rules, pepsico_news) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', %u, '%s')", $fname, $lname, $email, $phone, $state, $dob, $rules, $pepsico_news);

?>

What seems to be happening is that, when performing the replacement of values in sprintf , no you are adding quotes , so your sql query would be left with errors.

Look at this example:

<?php

$fname = "Juan";
$lname = "Perez";
$email = "[email protected]";
$phone = "123456";
$state = "UK";
$dob = "dob";
$rules = 1;
$pepsico_news = "pepsico";

$sql = sprintf("INSERT INTO users (firstname, lastname, email, phone, state, dob, rules, pepsico_news) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', %u, '%s')", $fname, $lname, $email, $phone, $state, $dob, $rules, $pepsico_news);

print $sql;

?>

If we get the result, it will give us something like this:

  

INSERT INTO users (firstname, lastname, email, phone, state, dob, rules, pepsico_news) VALUES ('Juan', 'Perez', '[email protected]', '123456', 'UK' , 'dob', 1, 'pepsico')

If you execute this query, it is very likely to work, since we have added all the quotes , for the varchar type fields.

But!

If we leave the same example, with the query as you have asked:

<?php

$fname = "Juan";
$lname = "Perez";
$email = "[email protected]";
$phone = "123456";
$state = "UK";
$dob = "dob";
$rules = 1;
$pepsico_news = "pepsico";

$sql = sprintf("INSERT INTO users (firstname, lastname, email, phone, state, dob, rules, pepsico_news) VALUES (%s, %s, %s, %s, %s, %s, %u, %s)", $fname, $lname, $email, $phone, $state, $dob, $rules, $pepsico_news);

print $sql;

?>

We would throw this:

  

INSERT INTO users (firstname, lastname, email, phone, state, dob, rules, pepsico_news) VALUES (Juan, Perez, [email protected], 123456, UK, dob, 1, pepsico)

And probably the query will not work, because in all the fields where a string was inserted, we are not adding the quotes . So the engine will tell you that error.

    
answered by 25.04.2017 / 18:33
source