将数据插入我的数据库不起作用

时间:2012-04-11 19:26:23

标签: php mysql database relational

我有一个很好的下拉列表工作,从表团队(FK)填充。唯一不起作用的是将数据添加到匹配项中。我一直收到以下错误:

- 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

有谁能告诉我导致这些错误的原因是什么?

请参阅下面的代码,我知道它很容易被sql注入,但我只想让它工作。

**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;
?>

3 个答案:

答案 0 :(得分:2)

试试这个

$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']));

答案 1 :(得分:1)

你的PHP无效:

$_POST[team_home]
双引号内的

错误。

围绕它放置{},并在team_home

周围添加单引号

{$ _ POST [ 'team_home']}

和其他领域类似。并且建议从SQL注入中了解到,并且在查询之前使用$ _POST清理数据

答案 2 :(得分:0)

只想指出你在这里做什么

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

非常危险。您不应该直接使用任何全局变量。您需要过滤它们并验证它们,或者您正在打开SQL注入攻击的应用程序。

相关问题