phpmysqlmysqlimysql-insert-idmysqli-multi-query

mysql insert statement inside a while statement adds only 1 record


I have this code (refer below)

$sql = "SELECT * FROM records";
$result = mysqli_query($this->db,$sql);

while($row = mysqli_fetch_assoc($result)){
    $itemid = $row['id'];
    $itemname = $row['itemname'];
    $itemdesc = $row['itemdesc'];
    $brand = $row['brand'];
    $serialno = $row['serialno'];
    $nostock = $row['nostock'];
    $price = $row['price'];
    $onsale = $row['onsale'];
    $poster = $row['poster'];
    $thedate = $row['thedate'];

    $sql = "INSERT INTO backupp SET id='$itemid', itemname='$itemname', itemdesc='$itemdesc', brand='$brand', serialno='$serialno', nostock='$nostock', price='$price', onsale='$onsale', poster='$poster', thedate='$thedate'";
    $result = mysqli_query($this->db,$sql) or die(mysqli_error($this->db));
    return $result;
}

as you can see from the above codes, it will first pull all the data from db table named "records" and then put each row into there corresponding variable and then insert the stored data (those data that has been pulled from db table name "records" and stored on there corresponding variable) to db table named "backupp". Now, the problem is, it only add one record to backup (the record that has been pulled first) which supposedly it should add all the pulled record from db table named records to db table named backup. why?? any suggestions, recommendations, clues and ideas would be greatly appreciated. Thank you!

PS: its like export and import to other table with same structure but I have my own reason why I want to do it this way and assume I already successfully connected to a database ($this->db) called "inventory" and there is db table name there such as "records" and "backupp" with same structure.


Solution

  • change your code into this (see below).

    $sql = "SELECT * FROM records";
    $result = mysqli_query($this->db,$sql);
    $x = 0;
    while($row = mysqli_fetch_assoc($result)){
    $itemid = $row['id'];
    $itemname = $row['itemname'];
    $itemdesc = $row['itemdesc'];
    $brand = $row['brand'];
    $serialno = $row['serialno'];
    $nostock = $row['nostock'];
    $price = $row['price'];
    $onsale = $row['onsale'];
    $poster = $row['poster'];
    $thedate = $row['thedate'];
    
    $sql = "INSERT INTO backupp SET id='$itemid', itemname='$itemname', itemdesc='$itemdesc', brand='$brand', serialno='$serialno', nostock='$nostock', price='$price', onsale='$onsale', poster='$poster', thedate='$thedate'";
    $result = mysqli_query($this->db,$sql) or die(mysqli_error($this->db));
    
    $x++;
    }