For循环只发布数组的前3个元素 - PHP

时间:2016-01-29 23:53:56

标签: php mysql

我有可能在其中包含无限量元素的数组。我试图将它们输入到我的数据库中,但它只输入数组的前3个元素。 我的数组看起来像这样

array(4) {
  ["ID"]=>
  array(5) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "3"
    [3]=>
    string(1) "4"
    [4]=>
    string(1) "5"
  }
  ["firstname"]=>
  array(5) {
    [0]=>
    string(5) "Steve"
    [1]=>
    string(3) "Dan"
    [2]=>
    string(3) "Jim"
    [3]=>
    string(4) "Adam"
    [4]=>
    string(5) "James"
  }
  ["surname"]=>
  array(5) {
    [0]=>
    string(5) "Smith"
    [1]=>
    string(6) "Colins"
    [2]=>
    string(6) "Knight"
    [3]=>
    string(5) "Lamar"
    [4]=>
    string(4) "Rays"
  }
  ["submit"]=>
  string(5) "Enter"
}

这是我的for循环和sql语句

$a[0] = $_SESSION['ID'];
$a[1] = $_SESSION['firstname'];
$a[2] = $_SESSION['surname'];


 for ($i = 0; $i<count($a); ++$i){
     $id = $_SESSION['ID'][$i];
     $fname = $_SESSION['firstname'][$i];
     $sname = $_SESSION['surname'][$i];

$query = "INSERT INTO orders(id, firstname, surname) VALUES('$id', '$fname', '$sname')";


if (mysqli_query($connection, $query)) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . mysqli_error($connection);
}
}

这只会发布每个数组的0,1,2个元素。如何更改它以便将所有元素插入到我的数据库中?

2 个答案:

答案 0 :(得分:2)

for ($i = 0; $i<count($a); ++$i)

此循环将进行三次,因为$a数组有3个项目(ID,名字,姓氏)。将count($a)更改为count($a[0]),它应该有效。虽然这不是最好的解决方案(如果这三个阵列中的一个具有比其他阵列更多/更少的项目怎么办?)

答案 1 :(得分:1)

你循环遍历$a数组有3个项目

尝试此解决方案

$a[0] = $_SESSION['ID'];
$a[1] = $_SESSION['firstname'];
$a[2] = $_SESSION['surname'];

$b = count($a[0]);

 for ($i = 0; $i<$b; ++$i){
     $id = $_SESSION['ID'][$i];
     $fname = $_SESSION['firstname'][$i];
     $sname = $_SESSION['surname'][$i];

$query = "INSERT INTO orders(id, firstname, surname) VALUES('$id', '$fname', '$sname')";


if (mysqli_query($connection, $query)) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . mysqli_error($connection);
}
}