【问题标题】:Insert values from -large- array into mysql?将-large-数组中的值插入mysql?
【发布时间】:2014-10-31 19:52:53
【问题描述】:
        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));

【问题讨论】:

  • 你有没有尝试过?你具体卡在哪里?为什么你的努力没有奏效?你读过我们的Help center吗?
  • VALUES 列表的每个项目周围都缺少括号:它是 VALUES ('12345671'), ('12345672'), ... 而不是 VALUES '12345671' , ... 如果您的 id 列具有数据类型 INT 那么也不需要在值周围加上单引号.使用参数化的预处理语句迁移到 mysqli 或 PDO 是个好主意。

标签: php mysql arrays insert


【解决方案1】:

这样做会导致列数不匹配 - 而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);

Preview

这将使生成的 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);

Preview

【讨论】:

    猜你喜欢
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    • 2014-06-17
    • 2016-05-26
    • 2013-03-05
    • 1970-01-01
    • 2017-12-07
    相关资源
    最近更新 更多