I'm trying to create a loop witch will allow me to insert form data without writing the code over and over again for each form, for each input, like this:
if(isset($_POST[$submit])){
$name = $_POST['fullname'];
$email = $_POST['email'];
$title = $_POST['title'];
$message = $_POST['message'];
$date = date("Y-m-d h:i:sa");
$sql = "INSERT INTO messages VALUES ('', '$name' , '$email', '$title' , '$message' ,'$date', 'NO', '', '')";
if (mysqli_query($conn, $sql)) {
echo "New record has been added successfully !";}
else
echo 'Error: ' . $sql . ':-' . mysqli_error($conn);}
so I tried to create FOREACH loop. I get a message that a new record has been created,
but it creates a record with only a date and no input data, except the 'message' and only when I remove the $date part.
that's one version:
$values = ["fullname", "email", "title", "message"];
if(isset($_POST[$submit])){
foreach ($values as $value) {
$posted = $_POST[$value];
$sql = "INSERT INTO $tablename ($value ) VALUES ('$posted' )";
}
$date = date("Y-m-d h:i:sa");
$sql = "INSERT INTO $tablename ($datename ) VALUES ('$date' )";
if (mysqli_query($conn, $sql)) {
echo "New record has been added successfully !";}
else
echo 'Error: ' . $sql . ':-' . mysqli_error($conn);}
that's the second:
if(isset($_POST['submit'])) {
$count=0;
$end = 4; //num of values to be inserted
foreach($_POST as $key => $val) {
$count ++;
$sql = "INSERT INTO $tablename ($key ) VALUES ('$val')";
if ($count == $end) break;
//instead
// if($key != $submit){
// $sql = "INSERT INTO $tablename ($key ) VALUES ('$val')";
// }
}
$date = date("Y-m-d h:i:sa");
$sql = "INSERT INTO $tablename ($datename ) VALUES ('$date')";
if (mysqli_query($conn, $sql)) {
echo "New record has been added successfully !";}
else {
echo 'Error: ' . $sql . ':-' . mysqli_error($conn);}
}
The name's in the Form are the same as the row names in the table.