I'm trying to figure out why this MYSQL INSERT inside the foreach doesn't insert anything into mysql database!
// Parse the form data and add inventory item to the system
if (isset($_POST['g_name'])) {
$g_name =$_POST['g_name'];
$numbers = $_POST['numbers'];
$comma_separated = explode(", ", $numbers);
foreach($comma_separated as $seperate){
$sql .="INSERT INTO groups(`g_name`, `numbers`) VALUES ('$g_name','$seperate')";
}
$query = mysqli_query($db_conx, $sql);
header("location: groups.php");
exit();
}
if I change the $sql .=
to $sql =
it inserts only one value in the MYSQL database.
the value of $numbers
is like this: 1, 2, 3, 4, 5
could someone please advise on this issue?
any help would be appreciated.
Change your loop so you execute the query each time:
foreach($comma_separated as $seperate){
$sql ="INSERT INTO groups(`g_name`, `numbers`) VALUES ('$g_name','$seperate')";
$query = mysqli_query($db_conx, $sql);
}
You should keep in mind that your script is at risk for SQL Injection Attacks. Learn about prepared statements.
You need to execute the query inside the loop for it to insert more than once.
<?php
foreach($comma_separated as $seperate) {
$sql = "INSERT INTO groups(`g_name`, `numbers`) VALUES ('$g_name','$seperate')";
$query = mysqli_query($db_conx, $sql);
}
?>
You should also consider using prepared statements.
Rather than trying to execute multiple queries, you can use this syntax for inserting multiple records with one query.
$sql = "INSERT INTO groups(`g_name`, `numbers`) VALUES";
$comma = '';
foreach($comma_separated as $seperate){
$sql .="$comma ('$g_name','$seperate')";
$comma = ',';
}
$query = mysqli_query($db_conx, $sql);
From the MySQL documentation:
INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas.
Example:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);