-2

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!

dean
  • 3
  • 3
  • You don't actually query anything, you just build the string in the loop. And why do you want the delay? – Qirel Jun 03 '17 at 10:50
  • You should always use prepare if you want to reuse the statement. Just creating a string does not do a query. – Markus Zeller Jun 03 '17 at 11:03
  • ah. I see my mistake. I want the delay so whenever the data was inserted into the database, the time would be different. thank you – dean Jun 03 '17 at 12:21

2 Answers2

0

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),
   ...;
Jenne
  • 864
  • 5
  • 11
0

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);
}
Alexios Tsiaparas
  • 880
  • 10
  • 17