2010-01-23 80 views
1

如何使用php在mysql中添加多条记录。使用数组是这个问题的唯一解决方案。因为我尝试使用数组,但会在数据库中添加的是这样的记录: 阵列如何使用php在mysql中添加多条记录

+1

你能提供更多的细节和你的代码源吗? – Zied 2010-01-23 13:56:13

回答

4

您可以使用多值插入语句(INSERT ... VALUES(RECORD1),(RECORD2)等) (见http://dev.mysql.com/doc/refman/5.1/en/insert.html

这是如何从记录

阵列构建这样一个说法
$values = array(); 
foreach($records_array as $record) 
    $values[] = sprintf("('%s' , '%s')", addslashes($record['name']), addslashes($record['email'])); 
$sql = "INSERT INTO users(name, email) VALUES " . implode(",", $values); 
mysql_query($sql); 
+0

一个很好的帖子,但注意:使用mysql_real_escape_string而不是addslashes !!!!!!! http://php.net/manual/en/function.mysql-real-escape-string.php – Dan 2010-01-23 18:24:56

+0

%s是什么意思? – user225269 2010-01-23 22:51:39

+0

它表示字符串替换params'addslashes($ record ['name'])''提供 – Pentium10 2010-01-24 10:59:02

3

你需要去通过阵列中的每个成员:

foreach($array as $record) 
{ ... } 

和执行INSERT查询每个成员或 - 更好的表现 - 按照user187291's answer中的说明在一个陈述中插入所有记录。

+0

将它全部作为一个查询执行会更好,而不必为每次迭代都击中数据库。没有? – 2010-01-23 14:34:51

+0

是的。 @ stereofrog的答案概述了如何。我不知道VALUES可以一次做多行! – 2010-01-23 14:44:18