Awesom-o
Awesom-o

Reputation: 612

php/mysql dynamic form fields are not inserted in my table

I have a form that has a variable number of input fields, and i now try to get these values in my database. I got this code from another question here and all the replies where implying that they got it working..so i think i'm doing something wrong here.

I get no error, it just enters one empty entry/row in my database every time i submit the form. The $_POST array is filled with all the data i need, it shows when i print_r it.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {


  if (
     !empty($_POST['homeTeam']) && !empty($_POST['awayTeam']) && !empty($_POST['homeWin']) && !empty($_POST['awayWin']) && 
     is_array($_POST['homeTeam']) && is_array($_POST['awayTeam']) && is_array($_POST['homeWin']) && is_array($_POST['awayWin']) && 
     count($_POST['homeWin']) === count($_POST['awayWin'])
  ) {
      $homeTeam_array = $_POST['homeTeam'];
      $awayTeam_array = $_POST['awayTeam'];
      $homeWin_array = $_POST['homeWin'];
      $awayWin_array = $_POST['awayWin'];

      for ($i = 0; $i < count($homeTeam_array); $i++) {

          $homeTeam = mysql_real_escape_string($homeTeam_array[$i]);
          $awayTeam = mysql_real_escape_string($awayTeam_array[$i]);
          $homeWin = mysql_real_escape_string($homeWin_array[$i]);
          $awayWin = mysql_real_escape_string($awayWin_array[$i]);

          $sql = "INSERT IGNORE INTO CalcOdds (homeTeam, awayTeam, homeWin, awayWin) VALUES ('$homeTeam', '$awayTeam', '$homeWin', '$awayWin')"; 
          $conn->query($sql);
          $conn->close();

      }
  }
  echo "<pre>";
  print_r($_POST);
  echo "</pre>";
  echo 'Done!';
}

?>

Upvotes: 0

Views: 145

Answers (2)

Kholy
Kholy

Reputation: 441

I think the problem is because you have $conn->close(); inside the for loop try to add it after the loop like this:

     for ($i = 0; $i < count($homeTeam_array); $i++) {

          $homeTeam = mysql_real_escape_string($homeTeam_array[$i]);
          $awayTeam = mysql_real_escape_string($awayTeam_array[$i]);
          $homeWin = mysql_real_escape_string($homeWin_array[$i]);
          $awayWin = mysql_real_escape_string($awayWin_array[$i]);

          $sql = "INSERT IGNORE INTO CalcOdds (homeTeam, awayTeam, homeWin, awayWin) VALUES ('$homeTeam', '$awayTeam', '$homeWin', '$awayWin')"; 
          $conn->query($sql);            
      }
      $conn->close();

Upvotes: 3

user9407009
user9407009

Reputation:

  1. Instead of doing !empty() I'd do isset()

  2. By the looks of things you haven't actually established a connection to your database.

  3. Make sure that the data actually gets through the if() statement by using a echo() for example.

Upvotes: 0

Related Questions