一种有效的方式来保存阵列及其钥匙到数据库 [英] An efficient way to save an Array and its Keys to a database
问题描述
我想很多的变量保存到数据库中,现在是越来越荒谬的。我使用PHP和MySQL。
I am trying to save lots of variables to a database and it is getting ridiculous now. I am using PHP and MySQL.
有没有一种方法,我可以得到数组值和数组键(数组键是完全一样的表列/字段名)一气呵成,而无需添加一个新的变量和表列对。
Is there a way, I can get the array value and the array keys (array keys are exactly the same as the table column/field names) in one go without having to add a new variable and table column pair.
说实话,我只需要只构建SQL字符串的帮助,剩下的就是设置为我。
To be honest, I just need help with constructing the SQL String only, the rest is setup for me.
我可以将新列添加到数据库中的表时,我要存储一个新的变量。
I can add the new column to the database table when I have to store a new variable.
感谢所有的帮助
推荐答案
如果你想创建阵列一个SQL查询,这可能帮助:
If you want to create a SQL query from your array, this might help:
// Sample array
$array = array(
'key1' => 'value1',
'key2' => 'value2'
...
'key10' => 'value10'
);
// Get and escape the keys
$keys = array_map('mysql_real_escape_string', array_keys($array));
// Escape the values
$array = array_map('mysql_real_escape_string', $array);
// Build query
$query = "INSERT INTO table(`".implode('`, `', $keys)."`) VALUES('".implode("', '", $array)."')";
mysql_query($query);
在这种情况下,查询将是这个样子:
In this case, the query would look something like this:
INSERT INTO
table(`key1`, `key2` ... `key10`)
VALUES
('value1', 'value2' ... 'value10')
如果你有一个多维数组(数组的数组),你可以创建如下的查询:
If you have a multidimensional array (an array of arrays) you can create a query as follows:
// Sample multidimensional array
$array = array(
array('key1' => 'value1', 'key2' => 'value2'),
array('key1' => 'value3', 'key2' => 'value4'),
array('key1' => 'value5', 'key2' => 'value6')
);
// Get and escape the keys
$keys = array_map('mysql_real_escape_string', array_keys(current($array)));
// Array to store values for the query
$values = array();
// Loop every row and insert into $values array
foreach($array as $row) {
// Escape all items
array_map('mysql_real_escape_string', $row);
$values[] = "('".implode("', '", $row)."')";
}
$query = "INSERT INTO table(`".implode('`, `', $keys)."`) VALUES ".implode(', ', $values);
mysql_query($query);
在这种情况下,生成的查询会是这样的:
And in this case, the resulting query would be something like this:
INSERT INTO
table(`key1`, `key2`)
VALUES
('value1', 'value2'),
('value3', 'value4'),
('value5', 'value6')
现在只有你不必担心正在创建相应的列到数据库的东西。
Now only thing you have to worry about is creating the corresponding columns to the database.
这篇关于一种有效的方式来保存阵列及其钥匙到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!