homermac
homermac

Reputation: 111

PHP loop adding Array[0] instead of data to MySQL db

I have a form which coaches can enter in multiple pitchers for games. The form allows users to add rows as needed and looks like this:

<tr><td><select name="pitcherteam[]" size="1">
<option>PLEASE SELECT TEAM
<option>Team 1
<option>Team 2
<option>Team 3
</select></td><td>
<input type=text size=50 name="pitcher[]"></td><td>
<select name="pitcherage[]" size="1">
<option>AGE
<option>8
<option>9
</select></td>
<td><input type="text" size=3 name="pitcherpitches[]"></td></tr>

The php code I am using loops through the pitchers and if they are not blank does an insert into the mysql db:

$size_array = count($_POST['pitcher']); 
for ($i=0; $i<$size_array; $i++){ 
    if($_POST['pitcher'][$i] != ''){
    $sql2="INSERT INTO pitchcounts (pitcherteam, pitcher, pitcherage, pitches)
VALUES
    ('$_POST[date]','$_POST[pitcherteam][$i]','$_POST[pitcher][$i]','
$_POST[pitcherage][$i]','$_POST[pitches][$i]')";

    if (!mysqli_query($con,$sql2))
      {
  die('Error: ' . mysqli_error($con));
  }
} 
}

The loop is actually updating the db - BUT - instead of the values from the form - it's putting in zeros and array markers like this:

pitcherteam pitcher pitcherage  pitches
Array[0]    Array[0]    0   0
Array[1]    Array[1]    0   0
Array[3]    Array[3]    0   0

Any ideas on what's going on? Thanks!

Upvotes: 0

Views: 79

Answers (1)

MDEV
MDEV

Reputation: 10838

Concatenate your strings and variables!

$date = trim(mysqli_real_escape_string($_POST['date'])); //example variable clean
$sql2=" INSERT INTO
            `pitchcounts`
            (`pitcherteam`, `pitcher`, `pitcherage`, `pitches`)
        VALUES
            ('".$date."','".$_POST['pitcherteam'][$i]."','".$_POST['pitcher'][$i]."'
            ,'".$_POST['pitcherage'][$i]."','".$_POST['pitches'][$i]."')";

You should also clean your inputs - you should never put $_POST data straight into a database.

When dealing with cleaning arrays, there is no need to loop through each value applying the cleaning method individually, for those cases you can make use of array_map

function clean($val)
{
     return trim(strip_tags(mysqli_real_escape_string($val)));
}
$pitchers = array_map('clean',$_POST['pitcher']);

However, as mentioned by HamZa below, the best way of dealing with situations like this is to use prepared statements. Though depending on your experience, this may require some extra time and effort in order to convert your code over to that style.

Table and field names should also be surrounded with backticks ` to avoid conflict with reserved keywords

In addition to cleaning variables, you will also do well to validate the inputs as well. Other specialised cleaning methods are available as well for example, for a numeric field call intval or floatval, as other string fixing methods would be unnecessary

Upvotes: 3

Related Questions