代码重写:通过 php 数组将多行插入 mysql [英] Code rewrite for: insert multiple rows via a php array into mysql
问题描述
这是参考此处发表的帖子:insert多行通过php数组导入mysql
This is in reference to the post made here: insert multiple rows via a php array into mysql
我的问题是,谁能更详细地解释一下?我不明白 $data
和 $row
是什么或做什么.
My question is, can anyone explain this in more detail? I dont understand what $data
and what $row
is or does.
我从一个表单中提取了许多变量,例如:$Customer = $_POST['Customer'];
所以如果有人可以展示如何使用带有多个变量的代码的示例,真是太好了.
I'm pulling in many variables from a form like: $Customer = $_POST['Customer'];
So if someone can show an example of how to use this code with multiple variables, it would be real nice.
$sql = array();
foreach( $data as $row )
{
$sql[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')';
}
mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $sql));
推荐答案
foreach 构造提供了一种简单的方法来迭代数组.foreach 仅适用于数组和对象,并且当您尝试将它用于具有不同数据类型的变量或未初始化的变量时会发出错误.
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.
在这段代码中,$data
是一个数组.在每次迭代中,foreach 会将当前行的值赋给 $row
.这相当于:
In this code, $data
is an array. On each iteration, foreach will assign the value of the current row to $row
. This is equivalent to:
for($i=0;$i<sizeof($data);$i++)
{
$row = $data[$i];
//use $row however u want
}
例如:
$data[0]['text'] = 'text for category1';
$data[0]['category_id'] = '1';
$data[1]['text'] = 'text for category2';
$data[1]['category_id'] = '2';
$data[2]['text'] = 'text for category3';
$data[2]['category_id'] = '3';
在使用这个 $data
变量运行你的 foreach 之后,如果你使用 var_dump($row)
,你会得到这样的结果:
After running your foreach using this $data
variable, if you use var_dump($row)
, you will get something like this:
array(3) {
[0] =>
string(25) "("text for category1", 1)"
[1] =>
string(25) "("text for category2", 2)"
[2] =>
string(25) "("text for category3", 3)"
}
最后一行将内爆这个数组来创建一个有效的mysql查询.
The last line will implode this array to create a valid mysql query.
PS:顺便说一下,mysql 扩展已被弃用.你应该学习mysqli - mysql改进或mysql pdo - php 数据对象
PS: By the way, mysql extension is deprecated. You should learn mysqli - mysql improved or mysql pdo - php data objects
这篇关于代码重写:通过 php 数组将多行插入 mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!