PHP - 在while循环中插入SQL

PHP  - 在while循环中插入SQL

问题描述:

I generated a random monster team from a table, and limited by 6. Now, I also want to insert the team into user_team which contains the fields m1,m2,m3,m4,m5,m6

Those represent Monster 1 to Monster 6. Now when I try to insert the generated monsters into the team, only the last Monster seems to be inserting into it while I all of my monsters to be inserted. http://prntscr.com/8zrj2

$sql = "SELECT * from monsterdata ORDER BY RAND() LIMIT 6"; 
$result = mysql_query($sql);
// this checks if you have a result
if ($result == null) echo "No result";
else {  
    while (($row = mysql_fetch_array($result)) != false) {
$row = mysql_fetch_array($result);
{
// html code here
}
}

the Insert statement is $monster = $row['id']; $sql = "INSERT into user_team(m1,m2,m3,m4,m5,m6) VALUES('$monster','$monster','$monster','$monster','$monster','$monster')"; $result = mysql_query($sql);

Just don't know where/how to place it so it inserts the right values into the right columns.

我从表中生成了一个随机怪物团队,并受到6的限制。现在,我还要插入团队 进入user_team,其中包含字段 m1,m2,m3,m4,m5,m6 p>

这些代表怪物1到怪物6.现在当我尝试将生成的怪物插入团队时 当我插入所有怪物时,只有最后一个怪物似乎插入其中。 http:// prntscr。 com / 8zrj2 p>

  $ sql =“SELECT * from monsterdata ORDER BY RAND()LIMIT 6”;  
 $ result = mysql_query($ sql); 
 //这会检查你是否有结果
if($ result == null)echo“No result”; 
else {
 while(($ row = mysql_fetch_array(  $ result))!= false){
 $ row = mysql_fetch_array($ result); 
 {
 // html code here 
} 
} 
  code>  pre> 
 
  

Insert语句是 $ monster = $ row ['id']; $ sql =“INSERT into user_team(m1,m2,m3,m4,m5,m6)VALUES('$ monster ','$ monster','$ monster','$ monster','$ monster','$ monster')“; $ result = mysql_query($ sql); code> p>

只是不知道放在哪里/如何放置它所以它将正确的值插入到右列。 p> div>

If it were me, I would push the ids into an array and then use that like so:

$monsterIds = array();
while(($row = mysql_fetch_array($result)) !== false) {
    $monsterIds[] = $row['id'];
}
mysql_query("INSERT INTO user_team (m1, m2, m3, m4, m5, m6) VALUES ('{$monsterIds[0]}', '{$monsterIds[2]}', '{$monsterIds[3]}', '{$monsterIds[4]}', '{$monsterIds[5]}')") or die(mysql_error());

Also, don't forget to use the triple equals when comparing row results so that you don't get caught by a weird bug where things evaluate to false that aren't actually false (=== is the way to go with many functions which might return either an array, integer, or a boolean depending on the outcome).

The values will be placed in the columns in the order they are supplied.

Here is my example using PDO (php library):

$DBH = new PDO("mysql:host=$db_host;dbname=$db_name", $username, $password);
$webContractList=$DBH->query('SELECT id,nume,data FROM user2')->fetchAll();

$STH=$DBH->prepare("INSERT INTO user (id,nume,data) VALUES (:id ,:nume , :data)");

foreach ($webContractList as $item){           
    $STH->execute(array(':id'=>$item['id'],
                ':nume'=>$item['nume'],
                ':data'=>date('Y-m-d',strtotime($item['data']))));
}