保存PHP数组到MySQL? [英] Save PHP array to MySQL?
问题描述
什么是数据数组保存到一个MySQL的领域的好办法?
What is a good way to save an array of data to a single mysql field?
此外,一旦我查询在mysql表阵列,有什么好办法把它找回来到数组的形式?
Also once I query for that array in the mysql table, what is a good way to get it back into array form?
是序列化和反序列化的答案?
Is serialize and unserialize the answer?
推荐答案
有没有的好的办法数组存储到一个字段。
There is no good way to store an array into a single field.
您需要检查你的关系数据和对您的架构进行适当的修改。见这个方法参考下面的例子。
You need to examine your relational data and make the appropriate changes to your schema. See example below for a reference to this approach.
如果您的必须的数组保存到一个单场那么 连载()
和 反序列化()
功能会做的伎俩。但你不能实际内容进行查询。
If you must save the array into a single field then the serialize()
and unserialize()
functions will do the trick. But you cannot perform queries on the actual content.
作为替代的序列函数还有 json_en code()
和的 json_de code()
。
As an alternative to the serialization function there is also json_encode()
and json_decode()
.
考虑以下阵列
$a = array(
1 => array(
'a' => 1,
'b' => 2,
'c' => 3
),
2 => array(
'a' => 1,
'b' => 2,
'c' => 3
),
);
要保存在数据库中,你需要创建一个这样的表
To save it in the database you need to create a table like this
$c = mysql_connect($server, $username, $password);
mysql_select_db('test');
$r = mysql_query(
'DROP TABLE IF EXISTS test');
$r = mysql_query(
'CREATE TABLE test (
id INTEGER UNSIGNED NOT NULL,
a INTEGER UNSIGNED NOT NULL,
b INTEGER UNSIGNED NOT NULL,
c INTEGER UNSIGNED NOT NULL,
PRIMARY KEY (id)
)');
要与记录工作,你可以执行查询,如这些(是的,这是一个例子,当心!)
To work with the records you can perform queries such as these (and yes this is an example, beware!)
function getTest() {
$ret = array();
$c = connect();
$query = 'SELECT * FROM test';
$r = mysql_query($query,$c);
while ($o = mysql_fetch_array($r,MYSQL_ASSOC)) {
$ret[array_shift($o)] = $o;
}
mysql_close($c);
return $ret;
}
function putTest($t) {
$c = connect();
foreach ($t as $k => $v) {
$query = "INSERT INTO test (id,".
implode(',',array_keys($v)).
") VALUES ($k,".
implode(',',$v).
")";
$r = mysql_query($query,$c);
}
mysql_close($c);
}
putTest($a);
$b = getTest();
的连接()
函数返回一个MySQL连接资源
The connect()
function returns a mysql connection resource
function connect() {
$c = mysql_connect($server, $username, $password);
mysql_select_db('test');
return $c;
}
这篇关于保存PHP数组到MySQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!