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

最后发布: 2012-04-11 19:26:23


问题

我有一个不错的下拉列表,正在从表团队(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;
?>
php mysql database relational
回答

尝试这个

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


回答

您的PHP无效:

$_POST[team_home]

内双引号是错误的。

将{}括起来,并在team_home周围加上单引号

{$ _POST ['team_home']}

其他领域也是如此。 作为建议,请注意SQL注入,并在查询之前使用$ _POST清除数据


回答

只想指出你在这里做什么

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

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