本文介绍了如何使用php将数据数组插入mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当前,当通过print_r();输出时,我有一个类似于以下内容的数组:
Currently I have an Array that looks like the following when output thru print_r();
Array
(
[0] => Array
(
[R_ID] => 32
[email] => [email protected]
[name] => Bob
)
[1] => Array
(
[R_ID] => 32
[email] => [email protected]
[name] => Dan
)
[2] => Array
(
[R_ID] => 32
[email] => [email protected]
[name] => Paul
)
[3] => Array
(
[R_ID] => 35
[email] => [email protected]
[name] => Mike
)
)
我想将此数据插入到一个表中,每个元素值都属于其各自的字段.
I would like to insert this data into one table with each element value belonging to its respective field.
当前我的php代码如下所示
Currently my php code looks like the following
if(is_array($EMailArr)){
foreach($EMailArr as $R_ID => $email => $name){
$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) values ('$R_ID', '$email', '$name')";
mysql_query($sql) or exit(mysql_error());
}
}
*注意:R_ID不是此表中的主键.*
*Note : R_ID is NOT the primary key in this table.*
有人可以帮助我了解如何应对这种情况吗?感谢您的阅读和帮助!
Can someone help me understand how I should approach this situation? Thank you for reading and your help!
致谢.
推荐答案
我会避免对每个条目进行查询.
I would avoid to do a query for each entry.
if(is_array($EMailArr)){
$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) values ";
$valuesArr = array();
foreach($EMailArr as $row){
$R_ID = (int) $row['R_ID'];
$email = mysql_real_escape_string( $row['email'] );
$name = mysql_real_escape_string( $row['name'] );
$valuesArr[] = "('$R_ID', '$email', '$name')";
}
$sql .= implode(',', $valuesArr);
mysql_query($sql) or exit(mysql_error());
}
这篇关于如何使用php将数据数组插入mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!