dongranding3909 2018-09-27 14:49
浏览 142
已采纳

从For循环创建多个SQL数据

I am trying to add random x and y values to a MySQL database but strangely it only seems to ever add one value. I was looking at many of the other posts of similar issues on Stackoverflow and it just seemed they did not have query within the loop was the common issue. I do have the query in the loop and am unsure why it is still not working.

Please see my code below:

<?php 
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myTable";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
for ($i = 0; $i <= 100; $i++){
    $x = rand(0,20);
    $y = rand(0,200);
    $sql = "INSERT INTO data (x, y)"
    $sql .= "VALUES ($x, $y);";
    //mysql_query($sql);

    if ($conn->multi_query($sql) === TRUE) {
        echo "New records created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

$conn->close();
?>
  • 写回答

3条回答 默认 最新

  • doulu1907 2018-09-27 15:28
    关注

    I edited your for loop to look something like this, and it worked perfectly fine for me.

    for ($i = 0; $i <= 100; $i++){
        $x = rand(0,20);
        $y = rand(0,200);
        $sql = "INSERT INTO data (x, y) VALUES ('$x', '$y')";
        $result = mysqli_query($conn, $sql);
        if($result)
        {
            echo "Successfully created record " . $i;
        } else
        {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
        ob_start();
        ob_flush();
        flush();
        usleep(001000);
        ob_flush();
        flush();
    }
    

    it Delay's the loop by just a little like a fifth of a second in total. The reason I have delayed the iteration is because your database might have a limit on how many queries can be sent within a time frame. It works for me let me know if it works for you.

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

报告相同问题?

悬赏问题

  • ¥15 vscode问题请教
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM