You need to be building up the VALUES
section of your SQL in a loop and then executing a single query. So something like this:
$con = mysqli_connect("","","","");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
multiformpost($con);
mysqli_close($con);
function multiformpost($db) {
if(empty($db) {
throw new Exception('You need to pass a valid mysqli connection to this method');
}
$sql = "INSERT INTO podcasts(Episode, Date, Guest, Type, Youtube, MP3, Itunes) VALUES ";
$size = count($_POST['Episode']);
for ($x = 0; $x < $size; $x++) {
$Episode = mysqli_real_escape_string($db,$_POST['Episode'][$x]);
$Date = mysqli_real_escape_string($db,$_POST['Date'][$x]);
$Guest = mysqli_real_escape_string($db,$_POST['Guest'][$x]);
$Type = mysqli_real_escape_string($db,$_POST['Type'][$x]);
$Youtube = mysqli_real_escape_string($db,$_POST['Youtube'][$x]);
$MP3 = mysqli_real_escape_string($db,$_POST['MP3'][$x]);
$Itunes = mysqli_real_escape_string($db,$_POST['Itunes'][$x]);
$sql .= "('{$Episode}', '{$Date}', '{$Guest}', '{$Type}', '{$Youtube}', '{$MP3}', '{$Itunes}'),";
}
$sql = rtrim($sql,',');
if (!mysqli_query($db, $sql)) {
die ('Error: ' . mysqli_error($db));
}
echo "Added to database";
}
Note that I also made the following changes which I also suggest:
- I pass in DB connection to the function. I have no idea what your original parameter was being used for, since you can detect the array size of the POST arrays directly in the function. You would be even better served moving to object-oriented mysqli usage (as you could then verify an instantiate mysqli object was passed to the function), but I didn't make that change here.
- I differentiated the use of
$con
(for global scope) and$db
(for local sope in function) so that you do not confuse the two. Previously, your code referenced$con
inside function scope without declaringglobal
so that variable would not have even been available. This dependency injection approach is highly recommended as opposed to usingglobal
. - I moved DB connection error checking outside the function
- I added string escaping to mitigate against SQL injection.
- I moved all your global script elements together, as functions typically should not be inserted in the middle of procedural code like you have done, as that make the code more difficult to follow.