dsc56927
dsc56927
2017-06-03 10:48

在循环中将数据插入mysql数据库[重复]

已采纳

This question already has an answer here:

Im new to php and sql language and i got a question. I want to insert my data into the database while looping. So far, my code is like this.

for ($x = 0; $x <= 10; $x++) {
$sql="INSERT INTO exec (time, value) VALUES (now(), '34')";
}

However, when I execute this code, the data only insert into the database once and not 10 as I intended. I also want to add some delay around 10 seconds between each loop. Any help would be appreciated!

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • duan19780629 duan19780629 4年前

    You need a connection to the database and the actual insert.

    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    $stmt = $dbh->prepare("INSERT INTO exec (time, value) VALUES (now(), 34)");
    for ($x = 0; $x <= 10; $x++) {
       $stmt->execute();
       sleep(1);
    }
    
    点赞 评论 复制链接分享
  • dqdfpmmi022763 dqdfpmmi022763 4年前

    You are not running the query, you are just setting a variable to a string. Thus when the loop ends the string has the last query which is just the one row and it will execute that.

    Use string concatenation like $sql .= "INSERT ...;"; Remember to add a ; to the end of your sql statement to allow for multiple queries at the same time.

    As an alternative one could also insert multiple values with one insert statement like eg.:

    INSERT INTO `table_name`
       (`field1`, `field2`)
    VALUES
       (1, 2),
       (3, 4),
       ...;
    
    点赞 评论 复制链接分享