Reputation: 4557
I am writing a php script for creating serialized array as follow:
$x=Array();
$x[0]=$_GET['fname'];
$x[1]=$_GET['lname'];
$str=serialize($x);
print $str;
$y=$_GET['hf'];
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("formdemo", $con);
$sql="update rohit set data='$str' where fid='$y'";
now I want to append more data on this array. what should I do for that
Thanx
Upvotes: 0
Views: 3016
Reputation: 18290
Pull it out of the DB, unserialize it, add data, serialize it, then update it again:
$mysqli = new mysqli("localhost", "root", "", "formdemo");
$stmt = $mysqli->prepare("SELECT data FROM rohit WHERE fid = ?");
$stmt->bind_param('i', $_GET['hf']);
$stmt->execute();
$stmt->bind_result($x);
$stmt->fetch();
$stmt->close();
$x = unserialize($x['data']);
$x[] = "new data";
$x = serialize($x);
$stmt = $mysqli->prepare("update rohit set data=? where fid=?");
$stmt->bind_param('si', $x, $_GET['hf']);
$stmt->execute();
Upvotes: 0
Reputation: 152206
First of all, you do not escape data passed to your script. You have to do it with:
$x[0] = mysql_real_escape_string( $_GET['fname'] );
Also you do not need to set index, so:
$x[] = mysql_real_escape_string( $_GET['fname'] );
It will append data to the end of array.
If you want to add new data to the existing serialized array, you need to unserialize it, add data and serialize again:
$x = unserialize($x);
$x[] = 'something else';
$x = serialize($x);
Upvotes: 0
Reputation: 6204
You must unserialized array add value and serialize again.
function add($serializedArray, $item)
{
$array = unserialize($serializedArray);
$array[] = $item;
return serialize($array);
}
Upvotes: 1