PHP无法添加或更新子字段 - 外键错误

时间:2012-05-29 01:53:56

标签: php html mysql

我在尝试将某些值插入MySQL数据库时收到错误 - 我的页面当前读取了通过URL传递的值'EventID',并允许我根据该EventID添加结果。我目前有一个下拉框,由成员表中的成员填充 我得到了这个可怕的错误:

  

无法添加或更新子行:外键约束失败(clubresultsresults,CONSTRAINT ResultEvent FOREIGN KEY(EventID)参考eventsEventID)ON DELETE CASCADE)

我无法更改表格结构,因此非常感谢任何帮助。 注意 - 我现在正在使用它来回显SQL,以找出它不会插入的错误。

<?php

error_reporting (E_ALL ^ E_NOTICE); 
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("clubresults", $con);

   // Get id from URL
    $id = mysql_real_escape_string($_GET['EventID']);

    // If id is number
    if ($id > 0) 
    {
         // Get record from database
         $sql = "
            SELECT EventID
            FROM results 
            WHERE EventID = " . $id;
         $result = mysql_query($sql); 
         }
if (isset($_POST['submit'])) {       
  $sql="INSERT INTO results (MemberID, Score, Place)
VALUES
('".$_POST['student']."', '".$_POST['Score']."', '".$_POST['Place']."')";

$add_event = mysql_query($sql) or die(mysql_error());;

echo $add_event;
}

HTML表单 -                         

$_SERVER['PHP_SELF']?>" method="post"> 
                        <table border="0"><p>
                        <tr><td colspan=2></td></tr>
                        <tr><td>Member Name: </td><td>
                        <?php
                        $query="SELECT * FROM members";

/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */

$result = mysql_query ($query);
echo "<select name=student value=''>Student Name</option>";
// printing the list box select command

while($nt=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value='$nt[MemberID]'>$nt[Firstname] $nt[Surname]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box 
?>

                        <tr><td>Score:</td><td> 
                        <input type="text" name="Score" maxlength="10"> 
                        <tr><td>Place:</td><td> 
                        <input type="text" name="Place" maxlength="10"> 
                        </td></tr> 
                        <tr><th colspan=2><input type="submit" name="submit" 
                        value="Add Result"> </th></tr> </table>
                        </form>

1 个答案:

答案 0 :(得分:2)

您必须将EventID插入results记录:

$sql="INSERT INTO results (MemberID, Score, Place, EventID) VALUES (?, ?, ?, ?)";

注意我已使用?占位符代替您的$_POST变量(这使您容易受到SQL injection的攻击)。

您应该使用预先准备好的语句将变量作为参数传递给SQL,但是它们在您使用的古老MySQL扩展中不可用(社区拥有begun deprecating}无论如何,所以你真的应该停止用它编写新的代码);而是使用改进的MySQLi扩展名或PDO抽象层。