-2

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.

Paul T.
  • 3,118
  • 11
  • 19
  • 25
AndyR
  • 1
  • 1
  • I have a feeling you're trying to do some unnecessary abstraction, for the sake of not having to manually define columns in queries. That's a bad idea, because your code will be hard to follow and your forms will be dependent on your column names and vice versa. Stick to the most basic form. – El_Vanja May 07 '21 at 19:07
  • 1
    Aside from that, please note that the way you're writing your query is unsafe, as it's open to [SQL injection](https://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work). You should switch to [prepared statements](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) to prevent it. – El_Vanja May 07 '21 at 19:08
  • 1
    If you're only learning how to query a database, I would suggest [PDO](https://phpdelusions.net/pdo) over `mysqli`. A little more advanced and beginner friendly. – El_Vanja May 07 '21 at 19:11
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman May 07 '21 at 21:17
  • This is a really really bad idea. Do not do this. Don't trust user input. Your application needs to validate what it receives from the client – Dharman May 07 '21 at 21:18
  • well I didn't write a validation code here, that's because I just tried to create a function to insert the data quickly, validation in not the problem I want to solve here, but thanks anyway I will check the prepared statements and try to improve this code. – AndyR May 08 '21 at 13:28

0 Answers0