当前,当通过print_r()输出时,我有一个类似于以下内容的数组;
Array ( [0] => Array ( [R_ID] => 32 [email] => a@a.com [name] => Bob ) [1] => Array ( [R_ID] => 32 [email] => b@b.com [name] => Dan ) [2] => Array ( [R_ID] => 32 [email] => c@c.com [name] => Paul ) [3] => Array ( [R_ID] => 35 [email] => d@d.com [name] => Mike ) )
我想将此数据插入到一个表中,每个元素值都属于其各自的字段。
目前,我的php代码如下所示
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不是此表中的主键。
有人可以帮助我了解如何应对这种情况吗?感谢您的阅读和帮助!
问候。
我会避免对每个条目进行查询。
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()); }