开发者

trouble with quotes and mysql insert into

I'm having problems inserting a form $_POST variable to MySQL! I know it's a single quote problem but simply cannot resolve it.

Code is:

$naziv_db = $_POST["naziv"];
$naziv_db = mysql_real_escape_string($naziv_db);

$query = "INSERT INTO items (title) VALUES ('$naziv_db')";

$stmt = mysql_query($query) or die("MySQL error: " . mysql_error());
开发者_StackOverflow中文版

If I enter a value containing " it inserts correctly, but if it contains ' then the error appears!

For example if my input is Milky's

error is: MySQL 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 's

If my input is "Milkys" everything goes well...


I'm new here, so can't post an answer to my own question so i have to edit!

Christian's solution was the right one!

I have changed the code:

$query = "INSERT INTO items (title) VALUES ('$naziv_db')";

to:

$query = 'INSERT INTO `items` (`title`) VALUES ("'.$naziv_db.'")';

and now it accepts both " and ' without error!

Thank you guys, you're the best :D


To avoid this entirely, you'd be best using a prepared statement.

There's a good example in the answer to this question.

Converted for your case, you get:

$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("INSERT INTO items (title) VALUES (?)");
$stmt->bind_param('s', $_POST["naziv"]);
$stmt->execute();
$stmt->close();


It's quite impossible to get such an error from your code.
Most likely there is a typo somewhere in it.
May be you're escaping wrong variable or it's another query producing this error

Are you sure you posted the code you actually running? is it exact code or some sketch?

change your mysql_query string to this one

mysql_query($query) or trigger_error(mysql_error()." ".$sql);

and paste it's output please.

or, even change whole code:

ini_set('display_errors',1);
error_reporting(E_ALL);

$naziv_db = $_POST["naziv"];
$naziv_db = mysql_real_escape_string($naziv_db);
$query = "INSERT INTO items (title) VALUES ('$naziv_db')";

var_dump($_POST["naziv"]);
echo "<br>\n";
var_dump($naziv_db);
echo "<br>\n";
var_dump($query);
echo "<br>\n";

mysql_query($query) or trigger_error(mysql_error()." ".$sql);

this is called "debugging" and usually helps.


Try addslashes - it's made for parsing strings into database-friendly content.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜