我正在编写一个php脚本,用于创建序列化数组,如下所示:
$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'";
现在我想在这个数组上添加更多的数据。我该为做什么
Thanx
您必须将未序列化的数组添加值并再次序列化。
function add($serializedArray, $item)
{
$array = unserialize($serializedArray);
$array[] = $item;
return serialize($array);
}
首先,您不转义传递到脚本的数据。你必须使用
$x[0] = mysql_real_escape_string( $_GET['fname'] );
也不需要设置索引,所以:
$x[] = mysql_real_escape_string( $_GET['fname'] );
它将把数据附加到数组的末尾。
如果您想将新数据添加到现有的序列化数组中,则需要取消序列化,添加数据并再次序列化:
$x = unserialize($x);
$x[] = 'something else';
$x = serialize($x);
将其从数据库中取出,取消序列化,添加数据,序列化,然后再次更新:
$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();