while循环为mysqli结果

时间:2015-06-30 09:15:09

标签: php mysqli

所以我试图将一些记录从一个数据库插入另一个数据库。到目前为止,我有这个:

// $records_r = mysqli_fetch_assoc(mysqli_query($conn_r, "SELECT * FROM `TABLE_export` WHERE ID > 100"));   If do this -> it inserts only one record    

$records_r = mysqli_query($conn_r, "SELECT * FROM `TABLE_export` WHERE ID > 100");      

while (mysqli_fetch_array($records_r, MYSQL_ASSOC)) { //I need some while loop, but this is not working

    $values_r_implode = implode(",", array_values($records_r)); // I get an error:  array_values() expects parameter 1 to be array, object given in
    $values_r_array = explode(",", $values_r_implode);                  

    $stmt = $conn_i->prepare("INSERT INTO `TABLE_import` (`COLUMN1`, `COLUMN2`, `COLUMN3`) 
    VALUES (?,?,?)");       

    $stmt->bind_param("sss", $value1, $value2, $value3);

    $value1 = $values_r_array[0];
    $value2 = $values_r_array[1];           
    $value3 = $values_r_array[2];                   

    $stmt->execute();   
}

我只需要循环播放每个必须插入的新记录。

2 个答案:

答案 0 :(得分:1)

试试这个

$records_r = mysqli_query($conn_r, "SELECT * FROM `TABLE_export` WHERE ID > 100");      

while($row = mysqli_fetch_array($records_r)){ //I need some while loop, but this is not working

 $stmt = $conn_i->prepare("INSERT INTO `TABLE_import` (`COLUMN1`, `COLUMN2`, `COLUMN3`) 
VALUES (?,?,?)");

$value1 = $row[0];
$value2 = $row[1];           
$value3 = $row[2];  

$stmt->bind_param("sss",$value1, $value2, $value3);

 $stmt->execute();               


}

答案 1 :(得分:0)

为什么不使用1个查询?

阅读本文:http://dev.mysql.com/doc/refman/5.1/en/insert-select.html

这应该有效:

INSERT INTO TABLE_import(column1,column2,column3)   SELECT TE.Column1,TE.Column2,TE.Column3   FROM TABLE_export as TE WHERE TE.Id> 100;

另外,为什么不使用面向对象的编程。使它变得如此简单。校验: http://php.net/manual/en/mysqli.query.php

看那里的例子1。这样您就不必向每个查询/提取发送连接或查询变量。