2017-06-03 10:48



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!

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


  • 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++) {
    点赞 评论 复制链接分享
  • 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`)
       (1, 2),
       (3, 4),
    点赞 评论 复制链接分享