简体   繁体   中英

error when insert to varchar column

i have following qquery in MySQL

CREATE TABLE IF NOT EXISTS `adds` ( 
  `add_id` int(11) NOT NULL,
  `title` varchar(500) NOT NULL,
  `email` varchar(100) NOT NULL,
  `name` varchar(100) NOT NULL,
  `category` varchar(100) NOT NULL,
  `subcategory` varchar(100) NOT NULL,
  `district` varchar(100) NOT NULL,
  `city` varchar(100) NOT NULL,
  `discription` varchar(5000) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL,
  `price` varchar(100) NOT NULL,
  `address` varchar(500) NOT NULL,
  `mobile` int(11) NOT NULL,
  `date` date NOT NULL
) 

then i try to insert row via following code

$insert = mysql_query("insert into adds(title,email,name,category,subcategory,district,city,discription,price,address,mobile,date) values('$title','$email','$name','$cat','$subcat','$district','$city','$description','$price','$address','$mobile','$date')") or die(mysql_error());

now if i give a value to my description field like this= 'lk' :

this is cause to a error.so some one can tell me why is that?

When you construct your query, you need to escape the data you are inserting. You need to at least use addslashes() function in PHP, like this:

$insert = mysql_query("insert into adds(title,email) values('".addslashes($title)."','".addslashes($email)."')")

However more correct way is to use a different function than addslashes, which properly handles all characters in the data, not only apostrophes.

I am using my custom 'escape' function like this:

function escape($text)
{
   return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $text);
}

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