I'm converting an old script to be compliant with MySQLi and ran in to an issue...
$link = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$myQuery = "INSERT INTO table (name, description) VALUES ('$name', '$description')";
if (!mysqli_query($link, $myQuery)) {
printf('Error');
} else {
printf('Success');
}
mysqli_close($link);
This works fine, no errors. But when I add the mysqli_real_escape_string() I get an error...
$link = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$myQuery = "INSERT INTO table (name, description) VALUES ('$name', '$description')";
$myQuery = mysqli_real_escape_string($link, $myQuery);
if (!mysqli_query($link, $myQuery)) {
printf('Error');
} else {
printf('Success');
}
mysqli_close($link);
This returns an error:
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 '\'TestName\', \'TestDescription\' at line 1
Am I missing something simple? Quotes?
This line:
That isn't right.
You need to use
$name
variable and not the$myQuery
variable. That's what need escaping and not the whole query itself.However, ^
$myQuery
should be replaced with each of the variables being used to be inserted.Your query should look more like this:
Nota:
You may want to look into using
mysqli
with prepared statements, or PDO with prepared statements, they're much safer.Plus, just for argument's sake;
table
is a MySQL reserved word should that be the actual table's name and is required to be escaped:An example of a
mysqli
prepared statement:s
is for stringsAn example of a PDO prepared statement: