Search code examples
phpmysqldatabaserelational

Inserting data into my database isn't working


I've got a nice drop down list working which is getting populated from a the table teams (FK). The only thing that isn't working is adding the data into the matches. I keep getting the following errors:

- team_home not set 
- team_away not set 

- Notice: Undefined index: team_home in vvo/insertmatch.php on line 28

- Notice: Undefined index: team_away in vvo/insertmatch.php on line 28

- Error: You have an error in your SQL syntax; check the manual that corresponds to your    MySQL server version for the right syntax to use near 'matches (team_home, team_away) VALUES ('','')' at line 1

Can anyone tell me what is causing these errors?

See the code below, I know it's vulnerable for sql injection, but I'd just like to get this to work.

**addmatch.php**

<?php
$con = mysql_connect("db.xx.nl","md190851db210288","xxx");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("md190851db210288", $con);

?>
<form action="insertmatch.php" method="GET">
<select name="team_home">
<?php
$sql = "SELECT team_id, team_name FROM teams ".
"ORDER BY team_name";

$rs = mysql_query($sql);

while($row = mysql_fetch_array($rs))
{
  echo "<option value=\"".$row['team_id']."\">".$row['team_name']."</option>\n  ";
}
?>
</select>
<select name="team_away">
<?php
$sql = "SELECT team_id, team_name FROM teams ".
"ORDER BY team_name";

$rs = mysql_query($sql);

while($row = mysql_fetch_array($rs))
{
  echo "<option value=\"".$row['team_id']."\">".$row['team_name']."</option>\n  ";
}
?>
</select>
<input type="submit" />

**insertmatch.php**

<?php
  error_reporting(E_ALL);
  ini_set("display_errors", 1);

$con = mysql_connect("db.xx.nl","md190851db210288","xxx");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

if (isset($_POST['team_home'])) { 
    echo $_POST['team_home']; 
} else { 
    echo 'team_home not set <br>'; 
}
if (isset($_POST['team_away'])) { 
    echo $_POST['team_away']; 
} else { 
    echo 'team_away not set <br>'; 
}  

mysql_select_db("md190851db210288", $con);

$sql="INSERT INTO matches (team_home, team_away)
VALUES
('$_POST[team_home]','$_POST[team_away]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

echo $team_home;
?>

Solution

  • Try this

    $sql=sprintf("INSERT INTO matches (team_home, team_away)VALUES('%s','%s')",mysql_real_escape_string($_POST['team_home']),mysql_real_escape_string($_POST['team_away']));