user3548161
user3548161

Reputation: 119

Insert a row for each user mysql

Hi I have an array like the following but with 100 users.

$persons = array("rick", "tom", "harry");

I have a mysql table called mygamestats

Id  Person  points  date
 1  john     200    2017/05/01

I have a following insert statement

$points="200";
$date="2017/06/01";

$sql="INSERT INTO mygamestats (Person,points,date)VALUES ('$person','$points','$date')";

How can I insert into mygamestats table for each person in my persons array

$sql="INSERT INTO mygamestats (Person,points,date)VALUES ('$person','200','2017/06/01')";

My final output i trying to achieve is except its for 100's of users.

 Id  Person  points  date
 1  john     200    2017/05/01
 2  rick     200    2017/06/01
 3  tom      200    2017/06/01
 4  harry    200    2017/06/01

I read about batch insert or just using foreach key value loop any help much appreciated

Upvotes: 1

Views: 411

Answers (2)

GreensterRox
GreensterRox

Reputation: 7120

Use a foreach loop to concatenate the insert values:

<?php
$persons = array("rick", "tom", "harry");
$points="200";
$date="2017/06/01";

foreach($persons as $person){
    $values[] = "('".$person."','".$points."','".$date."')";
}

$sql = "INSERT INTO mygamestats (person,points,date) VALUES ".implode(",",$values);

var_dump($sql);
?>

Upvotes: 1

Prerak Sola
Prerak Sola

Reputation: 10009

You could use a foreach loop on your array and do it in the following way:

$points="200";
$date="2017/06/01";
$persons = array("rick", "tom", "harry");

foreach ($persons as $value) {
    $sql="INSERT INTO mygamestats (Person,points,date) VALUES ('$value','$points','$date')"; 
    //Now execute the above query
}

Upvotes: 1

Related Questions