2014-10-08 64 views
-3

我多阵列:插入多阵列数据库

阵列 (

[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')"); 
} 

但没有工作,

@:亚历山大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); 
}` 

$页是数组到数据库(限4页) $的HREF是multidimentions阵列状以上。

+0

你看过[错误](http://php.net/manual/en/mysqli.error.php)吗? – Marty 2014-10-08 06:05:11

回答

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')"); 
    } 
} 
+0

这应该解决问题! – 2014-10-08 06:14:24

+0

我跟着你,并得到错误:**无法在第159行**的file.php中获取mysqli。我的代码:'的foreach($的HREF作为$ HREF){ \t \t的foreach($ HREF作为$密钥=> $值){ \t \t \t mysqli_query($ CON,“插入的网址('id','id_page' ,'url') \t \t \t \t \t \t VALUES('','$ key','$ value')“); \t \t}' – TriMinh 2014-10-08 06:39:26

+0

显示完整的代码,请参考。看起来你在mysqli连接期间有错误 – mochalygin 2014-10-08 07:07:33

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()); 
    } 
} 

问题得到解决。谢谢!

+0

好的,现在你可以接受我的答案 – mochalygin 2014-10-08 09:52:12