使用foreach循环php构建Mysql查询

时间:2013-08-17 18:48:25

标签: php mysql arrays

值位于多维数组中,如:

Array ( 
    [0] => Array (
        [fname] => CollectiveAccess
        [lname] => Administrator
        [username] => administrator
        )
    [1] => Array (
        [fname] => Jorge
        [lname] => Ghelman 
        [username] => jorgeghe 
        )
    [2] => Array (
        [fname] => Sebastian
        [lname] => Scarano
        [username] => sscarano
        )
)

这是我用来构建查询的循环:

foreach ($user_names as $value) {
    foreach ($value as  $value2) {
        echo $value2 . " "; //prints all values
        $query = "INSERT INTO users (username, fname, lname)
                  VALUES ('$value2', );";
    }
}

print_r($ query)显示只将$ value2中的最后一个值传递给查询。

INSERT INTO users (username, fname, lname) VALUES ('test1', ); 

我确定这是一个新手的错误,但无法弄清楚。 感谢

1 个答案:

答案 0 :(得分:1)

试试这个

foreach ($user_names as $value) {
    $query = "INSERT INTO users (username, fname, lname)
              VALUES ('{$value['username']}', '{$value['fname']}', '{$value['lname']}');";
    echo $query;
}