[wd_asp elements=’search’ ratio=’100%’ id=1]

Dynamic multiple insert of php array

14th September 2018

Php - Arrays

php codehaven

When you have a form that has multiple textboxes, mon-sun(column) for many people(row), it can be very difficult to add these to a database easily!

This should make the most sense!!!


real_escape_string($_POST['jobid']);

if(!empty($_POST['mon'])) {
foreach($_POST['mon'] as $check) {
$mon[] = $check;
}
}

if(!empty($_POST['tue'])) {
foreach($_POST['tue'] as $check) {
$tue[] = $check;
}
}

$cmon = count($mon); // how many times?

for($x = 0; $x < $cmon; $x++) { $str[] = "('$jobid','{$mon[$x]}','{$tue[$x]}')"; } $s = implode(',',$str); echo $sql = "INSERT INTO hours (jobid,mon,tue) VALUES $s"; if ($mysqli->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "
" . $sql->error;
}

?>