stdClass Object
(
[ids] => Array
(
[0] => 12345671
[1] => 12345672
[2] => 12345673
[3] => 12345674
[4] => 12345675
[5] => 12345676
[6] => 12345677
.
.
.
.
)
我有一个包含用户 ID 的长数组。我想将每个数组作为新行插入 mysql。怎么能做到这一点?
我试过这个,但它不起作用
$sql = array();
foreach( $content as $row ) {
$sql[] = '("'.$con->real_escape_string($row['ids']).'")';
}
mysql_query('INSERT INTO table (ids) VALUES '.implode(',', $sql));
这样做
会得到列计数不匹配 - table
是一个保留字,因为生成的查询将看起来像
INSERT INTO `table` (ids) VALUES 12345676, 12345677
这是错误的。
你需要你的结束查询是这样的;
INSERT INTO `table` (ids) VALUES (12345676), (12345677)
要使用 PHP 实现这一点,我们可以执行以下操作;
<?php
$a = array("ids" => array(1,2,3,4,5,6,7,8,9));
$input_lines = implode(",", $a['ids']);
echo preg_replace("/[0-9]/", "($0)", $input_lines);
预览
这将使生成的PHP代码
<?php
$a = array("ids" => array(1,2,3,4,5,6,7,8,9));
$input_lines = implode(",", $a['ids']);
$sql = "INSERT INTO `table` (ids) VALUES ". preg_replace("/[0-9]/", "($0)", $input_lines);
预览