将多个数组插入数据库

时间:2014-10-08 06:01:43

标签: php arrays mysqli

我有多个数组:

阵 (

[1] => Array
    (
        [0] => http://213b572-ba681bf9cc9e
        [1] => http://f057-4139-ac40-bc4449722ffc
        [2] => http://b-c151-4ba1-b7b7-842771c36d6b
        [3] => http://5a77fb-8fce-4793-868f-c9fd73524037
    )

[2] => Array
    (
        [0] => http://8-d832-4b34-a55b-da04ad8cdd09
        [1] => http://b38-6a60-4233-b207-f40fae2ef431
        [2] => http://3-f31c-49c4-87ee-fcada05a105f
        [3] => http://07514-e438-45e2-906e-b440cbcbf8dc
    )

......

[76] => Array
    (
        [0] => http://8-d832-4b34-a55b-da04ad8cdd09
        [1] => http://b38-6a60-4233-b207-f40fae2ef431
        [2] => http://3-f31c-49c4-87ee-fcada05a105f
        [3] => http://07514-e438-45e2-906e-b440cbcbf8dc
    )

我希望我的数据库是:

          | id | id_page | url |

          | 1    | 1       | http://jjjjjjjjj |

          | 2    | 1       | http://jjjjjjjjj|  

          ......

          | 1000 | 76      | http://jjjjjjjjj|  

我用:

foreach ($hrefs as $key => $href) {
    mysqli_query($con, "INSERT INTO urls(`id`, `id_page`, `url`) VALUES ('', '$key', '$href')");
}

但不行。

@:Aleksandr Mochalygin

mysqli_connect.php

`$con = mysqli_connect("localhost", "root", "", "vlbd");
mysqli_query($con, "set names 'utf8'");
//Check connection
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL:" . mysqli_connect_error();
}`

功能查询:

function insertUrlsToDb() {
global $con;

$pages = getPagesFromDb(); // pages array to database (limit 4 pages)
$hrefs = getHrefByPages($pages); // hrefs multidimentions array 

foreach ($hrefs as  $href) {
    foreach ($href as $key => $value) {
        mysqli_query($con, "INSERT INTO urls(`id`, `id_page`, `url`)
                    VALUES ('', '$key', '$value')");
    }
}
mysqli_close($con);
}`   

$ pages是数组到数据库(限制4页) $ hrefs是上面的multidimentions数组。

2 个答案:

答案 0 :(得分:1)

您有2级数组,因此需要使用foreach两次:

foreach ($hrefs as $idPage => $arrayHrefs) {
    foreach ($arrayHrefs as $href) {
        mysqli_query($con, "INSERT INTO urls(id,id_page,url) VALUES ('', '$idPage', '$href')");
    }
}

答案 1 :(得分:0)

好的,我使用循环:

foreach ($hrefs as  $key => $value) {
    foreach($value as $key1 => $value1) {
        $sql = "INSERT INTO urls(`id`, `id_page`, `url`)
                            VALUES('', '$key', '$value1')";
        mysqli_query($con, $sql) or die(mysqli_error());
    }
}

问题已解决。谢谢!