While loop for mysqli results

2020-01-19 09:22发布

So I am trying to insert some record from one database to another.. So far I have this:

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

All I need is to loop trough every new record that I have to insert.

标签: php mysqli
2条回答
聊天终结者
2楼-- · 2020-01-19 09:39

Why not use 1 query?

Read this: http://dev.mysql.com/doc/refman/5.1/en/insert-select.html

This should work:

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

Also why not use object oriented programming. Makes it so much easier. Check: http://php.net/manual/en/mysqli.query.php

Look at Example 1 there. That way you do not have to send connection or query variables to each query / fetch.

查看更多
Luminary・发光体
3楼-- · 2020-01-19 09:44

try this

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


}
查看更多
登录 后发表回答