Here's my table
id | total | adult | kid | babies
Here's my data to be inserted
total = 3, adult = 2, kid = 1, babies = 0
It should be inserted like
id | total | adult | kid | babies
1 | 3 | 1 | 0 | 0
2 | 3 | 1 | 0 | 0
3 | 3 | 0 | 1 | 0
How can i insert my data like the above structure ?
I tried like
for ($i=0; $i <$total ; $i++)
{
$query = "INSERT INTO trip(total, adult, kid, babies)
VALUES (
'".$total."',
'".$adult."',
'".$kid."',
'".$babies."'
)";
$mysqli->query($query);
}
It is always inserting the same data. But how can i insert the data like the one i given above ?
You need to have three different loops, one for adults, one for kids and one for babies:
//Prepare the insert statement.
$mysqli->prepare = "INSERT INTO trip(total, adult, kid, babies) VALUES (?, ?, ?, ?)";
//Bind some variables.
$mysqli->bind_param('iiii', $total, $flagAdult, $flagKid, $flagBaby);
//Insert the adults.
$flagAdult = 1;
$flagKid = 0;
$flagBaby = 0;
for ($i=0; $i<$adult; $i++)
{
$mysqli->execute();
}
//Insert the kids.
$flagAdult = 0;
$flagKid = 1;
$flagBaby = 0;
for ($i=0; $i<$kid; $i++)
{
$mysqli->execute();
}
//Insert the babies.
$flagAdult = 0;
$flagKid = 0;
$flagBaby = 1;
for ($i=0; $i<$babies; $i++)
{
$mysqli->execute();
}
Your code was vulnerable to SQL injection attacks, so I changed it to use bind_param
, see documentation here and here.
I asumed that the data is integers (since there are only 0 and 1), but if you in fact want to use strings for some reason you will need to change 'iiii'
(meaning four integers) to 'ssss'
(meaning four strings).