简体   繁体   中英

PHP, mysql_real_escape_string and MySQL query

I am getting an error with a query similar to this, but I have not figured out the problem:

$str = "rob's";
...
$query ="INSERT INTO tableName (name) VALUES (mysql_real_escape_string('$str')";

Edit:

I apologize. I made a mistake while reducing my code down; this is closer to what I have that is giving an error:

$str = "rob's";
...
$query ="INSERT INTO tableName (name) VALUES (('".mysql_real_escape_string($str)."')";

mysql_real_escape_string() is PHP, not MySQL. You need to get it out of the quotes

$query ="INSERT INTO tableName (name) VALUES ('".mysql_real_escape_string($str)."')";

Also, $str is a string, so in MySQL it needs to be surrounded by qoutes too, I added them. You already had this in place, but because the function needed to get out of the quotes, they had to be moved

$query ="INSERT INTO tableName (name) VALUES ('" . mysql_real_escape_string($str) . "'";

mysql_real_escape_string() is a PHP function. So in your MySQL query string you have to pass it like a variable:

$query ="INSERT INTO tableName (name) VALUES ('" . mysql_real_escape_string($str) . "')";

Read more here: http://php.net/manual/en/function.mysql-real-escape-string.php

I would recommend performing the mysql_real_escape_string() function prior to the insert query. There are known issues with attempting to strip characters during the query call . The code below I have utilized numerous times before and know it works. It would also help if you gave us the error you've been getting, are you using a mysql extension such as mysql*i*, and the real code you're using. "I made a mistake while reducing my code down; this is closer to what I have that is giving an error" doesn't really help narrow down the issue you're having since you possibly removed the piece that throws the error while reducing your code. Nevertheless, using what I have below should work for you just fine.

$str = $_POST['name'];
mysql_real_escape_string($str);
$query = "INSERT INTO tableName (name) VALUES (".$str.")";
mysql_query($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