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

How to INSERT simple PHP array into MySQL table?

我有两个 results/outputs 来自几个脚本。

脚本 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 table 中: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,

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

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

感谢您的想法!

你这里做的有点不对,需要explode the $unit on the basis of ',' instead of 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.";
}