简体   繁体   中英

PHP/MySQL - SQL syntax error?

Now when I submit the character ' I get the following error listed below other then that everything is okay when I submit words. I am using htmlentities() and I still get this error.

How can I prevent this error from happening is there a way I can allow or convert or stop the character ' form displaying as an error?

Here is the error I get.

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 '''')'

You need to escape the strings you are sending in your SQL queries.

For that, you can use the mysql_real_escape_string function.

For instance, your code might look like this (not tested, but something like this should do the trick) :

$str = "abcd'efh";
$sql_query = "insert into my_table (my_field) values ('" 
  . mysql_real_escape_string($str)
  . "')";
$result = mysql_query($sql_query);


Another solution (Will require more work, though, as you'll have to change more code) would be to use prepared statements ; either with mysqli_* or PDO -- but not possible with the old mysql_* extension.


Edit : if this doesn't work, can you edit your question, to give us more informations ? Like the piece of code that causes the error ?

You have to escape the strings, using the appropriate method. You didn't mention what PHP functions you used so it's hard to guess. You should post the relevant snippet of PHP, but here's a couple of examples:

$text = "x'x";

// MySQL extension
mysql_query($db, "INSERT INTO table VALUES ('" . mysql_real_escape_string($text, $db) . "')");

// MySQLi extension
$db->query("INSERT INTO table VALUES ('" . $db->mysql_real_escape_string($text) . "')");

// PDO's prepared statement
$stmt = $pdo->prepare('INSERT INTO table VALUES (:myvalue)');
$stmt->execute(array(
    'myvalue' => $text
));

// Another example
$stmt = $pdo->prepare(
    'SELECT *
       FROM users
      WHERE first_name = :first
        AND last_name  = :last'
);

$stmt->execute(array(
    'first' => 'John',
    'last'  => 'Smith'
));

foreach ($stmt as $row)
{
    echo $row['user_id'];
}

I strongly recommend using PDO 's prepared statements , it's shorter to type and easier to use in the long run.

put your SQL query into a variable eg

$query = "SELECT * FROM table WHERE field= ".mysql_real_escape_string($var)."";

echo $query;

$result = mysql_query($query);

you can then inspect what is actually sent to mysql as the query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM