【问题标题】:How to INSERT simple PHP array into MySQL table? [duplicate]如何将简单的 PHP 数组插入 MySQL 表? [复制]
【发布时间】:2016-02-04 04:45:14
【问题描述】:

我有来自几个脚本的两个结果/输出。

脚本 1 结果:

    print_r($unit);

OUTPUT =  

Array ( [0] => http://one.com, [1] => http://two.com, [2] => http://three.com/, )

脚本 2 结果:

    echo $item."<br>"; 

OUTPUT = 

http://one.com,
http://two.com,
http://three.com,

我很尴尬地未能将其中任何一个导入到只有两个字段的 MySQL 表中:ID 和 URL。

//Connect to MySQL...

// Attempt insert query execution

    $list=implode($unit);

    $sql = "INSERT INTO urls (url) VALUES ('$list')";
    if(mysqli_query($conn, $sql)){
        echo "Records added successfully.";
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
    }

    // Close connection
    mysqli_close($conn);

插入有效,但代码将所有 3 个 url 插入单个字段:

id  url
1   http://one.com,http://two.com,http://three.com,

脚本 1 和 2 的期望 MySQL 表结果:

id  url
1   http://one.com
2   http://two.com
3   http://three.com

感谢您的想法!

【问题讨论】:

  • $list=implode(",", $unit); 试试看。
  • @Fred-ii- :我认为他希望每条记录都有一行。
  • @MateoBarahona 10-4。 吃饱
  • @MateoBarahona 10-4 = “已确认”。 grazie =“谢谢”。 ;-)
  • @MateoBarahona prego(欢迎),今天的意大利语课就到这里了! (我打赌你已经知道了)(10-4,广泛用于世界服务领域,警察、陆军、海军等);-)

标签: php mysql insert sql-insert


【解决方案1】:

你这里做的有点不对,你需要explode在','基础上的$unit,而不是implode

在这里

if (is_array($unit)) {
    $unit = implode(',', $unit);
} // check if array, convert to string
$list = explode(',', $unit);
$stmt = mysqli_prepare($conn, "INSERT INTO urls(url)  VALUES (?)");
mysqli_stmt_bind_param($stmt, 's', $url);
foreach ($list as $url) {
    if (empty($url)) {
        continue;
    }

    mysqli_stmt_execute($stmt);
    echo "Records added successfully.";
}

【讨论】:

  • $list=implode(",", $unit); 我想我的意思是“爆炸”; 我的错
  • 你没有净化你的价值观。这非常危险。
  • 是的,但 OP 目前只想插入(这也可能是本地项目)@Terry
  • 本地项目不是使用草率代码的借口。
  • explode 导致“警告:explode() 期望参数 2 是字符串,给定数组...”,foreach 行导致“警告:为 foreach() 提供的参数无效... "
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-01
  • 1970-01-01
  • 2013-11-30
  • 2021-10-05
  • 2017-12-07
  • 1970-01-01
  • 2017-09-02
相关资源
最近更新 更多