简体   繁体   中英

Insert multiple rows with one QUERY

I had some problems to get information from SELECT sql and then to INSERT that kind of information into my database. The problem is now I cannot solve to insert multiple rows.

I got this, It only insert one item if a category has more items then one it also need to be inserted that amount of times

I get the items in one row now next to each other, but I want those among each other

if($log1 = $log->fetch_object())
    {
while($loco = $log->fetch_object())
    {
$item .= "$loco->itemname";
    }
$logss = "INSERT INTO log_drops(`item`, mobname, game, log_id, log_name)VALUES('$item', '$mobname', '$game', '$id', '$name')";
if($result1 = $db->query($logss));
}

Create VALUES string from the result you are getting. You need to modify little bit as per your requirement. But, below example will give you idea how to do this:

$items = '';
while($loco = $log->fetch_object()){
    $items .= '('.$loco->itemname.',';
    $items .= // Some other variables those you want to insert...
    $items .= $loco->xyz.'),';
}
$new_data = rtrim($items, ',');
$clause = "INSERT INTO log_drops(`item`, mobname, game, log_id, log_name)
           VALUES $new_data";

Then after you only need to execute only one insert query.

Try this style, always i used to get my value out of array and create sql

<?php
$values = '';  // store values to be inserted
$n=','; // string to manage  comma between chunk of values to be inserted
$numberOfValues=5; // values defind to be inserted
$count = 0;
$recordNum =mysqli_num_rows($log) - 1; //count number of records from 0
while($loco = $log->fetch_object()){
    if($count == $recordNum){ $n = ' '; }
    $values .= "('$loco->itemname','$loco->game','$loco->game','$loco->log_id','$loco->log_name') $n ";
    $count++;
}

$clause = "INSERT INTO log_drops(`item`, mobname, game, log_id, log_name)
           VALUES $values";
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM