如何将简单的PHP数组插入MySQL表?

时间:2015-11-03 21:12:24

标签: php mysql insert sql-insert

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

脚本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个网址插入到单个字段中:

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

脚本1和2的DESIRED MySQL表结果:

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

感谢您的想法!

1 个答案:

答案 0 :(得分:3)

你在这里做错了,你需要 explode $unit基于','代替 implode < /强>

这里是

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

    if(mysqli_stmt_execute($stmt)){
        echo "Records added successfully.";
        mysqli_stmt_close($stmt);
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
    }
}