ppp ppp - 6 months ago 27
SQL Question

how to insert serialized data into database?

here my code-

$things = serialize($_POST['things']);
echo $things;

require 'database.php';

$q = "INSERT INTO tblslider(src) values($things)";
mysql_query($q, $link);

if($result)
{
echo "Slider saved successfully.";
}


Output-

a:4:{i:0;s:10:"651603.jpg";i:1;s:11:"7184512.jpg";i:2;s:11:"3659637.jpg";i:3;s:10:"569839.jpg";}v


it means I am getting the record properly but why it it not getting saved in db??

Answer

You forgot quotes around $things:

$q = "INSERT INTO tblslider(src) values('" . mysql_real_escape_string($things) . "')";

The mysql_real_escape_string() is really the least you should ever do!

Also as @sanders mentions, you should always output your complete query (via print_r() or var_dump()) as a first step in debugging.


I prefer to build queries like this to enhance readability:

$q = sprintf(
         'INSERT INTO tblslider(src) VALUES ("%s")',
         mysql_real_escape_string($things)
     );

That is, whenever I absolutely have to build and escape them myself. You should really have a look at PDO.


EDIT
Comments in this thread suggests that OP actually wants to insert 651603.jpg,7184512.jpg,3659637.jpg,569839.jpg into the database. In that case implode() could be used (provided that $_POST['things'] only contains items to insert!):

$q = sprintf(
         'INSERT INTO tblslider(src) VALUES ("%s")',
         mysql_real_escape_string(implode(',', $_POST['things']))
     );

Note, that I'm using $_POST['things'] directly here. No serialize(). (I did, however, not realize this erro until just now.)

Comments