简体   繁体   中英

PHP serialize & mysql_real_escape_string issue

I'm trying to add serialize array into database in wordpress, but I found that some of the content unable to retrieve, is returning false with using var_dump() to check the unserialize array.

My question: Is it enough to use mysql_real_escape_string to convert those special characters? Is it a better way to handle the serialize array compare to the process below?

// create array
$array = array(
    "title" => mysql_real_escape_string( $_POST['title'] ),
    "description" => mysql_real_escape_string( $_POST['description'] ),
    "datetime" => mysql_real_escape_string( $_POST['datetime'] )
);
// serailize
$array = maybe_serialize($array);
// insert into database
$wpdb->insert("mytable", array("ID"=>NULL, "content"=>maybe_serialize($array)));

Apart from the fact you are serializing twice in your example, I would serialize first, and then escape resulting string. If you use a prepared statement it will do the escaping for you. This means less calls to the escape function, and also I personally try to keep data un-escaped for as long as possible. It makes future code maintenance easier.

However assuming you can't use PDO (I'm not familiar with WP)....

$a = array(
  'title' => $_POST['title'],
  'description' => $_POST['description'],
  'datetime' => $_POST['datetime'],
);
$serialized = serialize( $array );
// insert into database
$wpdb->insert("mytable",
  array( 
   "ID"=>NULL,
   "content"=>mysql_escape_string($serialized),
  )
);

On another note, I would store the title, description, etc in separate fields if possible (I realize it may not be).

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