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 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题