douzhao4071 2012-05-08 04:39
浏览 91
已采纳

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.

  • 写回答

2条回答 默认 最新

  • duanguanya3052 2012-05-08 04:50
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序