没有创建外键

时间:2013-01-05 15:30:23

标签: mysql sql database

  

问题:

     

想要在下面执行选择查询(必须是此查询):

     

SELECT QuestionId FROM Question WHERE(QuestionNo =?AND SessionId =   ?)

     

为了能够在问题表中找到QuestionId并且   将它存储在答题表中以获取所有答案,以便我们可以   确定哪些答案属于哪个问题

问题:

mysqli代码的问题是它无法插入正确的QuestionId值。它在Answer表中为QuestionId显示0。那么有人可以解决这个问题,以便能够显示正确的QuestionId吗?

必须完成顶部提供的SELECT查询。我必须在mysqli中使用它。

以下是db表:

问题表

QuestionId (auto)  SessionId  QuestionNo
4                  2          1
5                  2          2
6                  2          3

答案表:

AnswerId (auto)  QuestionId  Answer
7                0           A
8                0           C
9                0           A
10               0           B
11               0           True

答案表应该是什么样的:

AnswerId (auto)  QuestionId  Answer
7                4           A
8                4           C
9                5           A
10               5           B
11               6           True

以下是代码:

 $questionsql = "INSERT INTO Question (SessionId, QuestionNo) 
    VALUES (?, ?)";
if (!$insert = $mysqli->prepare($questionsql)) {
    // Handle errors with prepare operation here
    echo __LINE__.': '.$mysqli->error;
}

 $answersql = "INSERT INTO Answer (QuestionId, Answer) 
    VALUES (?, ?)";
if (!$insertanswer = $mysqli->prepare($answersql)) {
    // Handle errors with prepare operation here
    echo __LINE__.': '.$mysqli->error;
}



//make sure both prepared statements succeeded before proceeding
if( $insert && $insertanswer)
{
    $sessid =  $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');
    $c = count($_POST['numQuestion']);

    for($i = 0;  $i < $c; $i++ )
    {


            $insert->bind_param("ii", $sessionid, $_POST['numQuestion'][$i]);

            $insert->execute();

            if ($insert->errno) 
            {
                // Handle query error here
                echo __LINE__.': '.$insert->error;
                break 1;
            }
}

        $results = $_POST['value'];
        foreach($results as $id => $value) 
        {
            $answer = $value;

            $lastID = $id;

            $questionidquery = "SELECT QuestionId FROM Question WHERE (QuestionNo = ? AND SessionId = ?)";

        if (!$questionidstmt = $mysqli->prepare($questionidquery)) {
        // Handle errors with prepare operation here
          echo __LINE__.': '.$mysqli->error;
        }


        // Bind parameter for statement
        $questionidstmt->bind_param("ii", $lastID, $sessionId);

        // Execute the statement
        $questionidstmt->execute();

                    if ($questionidstmt->errno) 
                    {
                        // Handle query error here
                        echo __LINE__.': '.$questionidstmt->error;
                        break 2;
                    }

        // This is what matters. With MySQLi you have to bind result fields to
        // variables before calling fetch()
        $questionidstmt->bind_result($quesid);

        // This populates $optionid
        $questionidstmt->fetch(); 

        $questionidstmt->close(); 



            foreach($value as $answer) 
            {
                $insertanswer->bind_param("is", $quesid, $answer);

                $insertanswer->execute();

                if ($insertanswer->errno) {
                    // Handle query error here
                    echo __LINE__.': '.$insertanswer->error;
                    break 3;
                }
            }
        }


    //close your statements at the end


    $insertanswer->close();
    $insert->close();
}

?>

1 个答案:

答案 0 :(得分:1)

您需要在INSERT之后直接检索用作Question中自动增量id的序列的最后一个值 - 使用LAST_INSERT_ID()SQL函数执行此操作。然后,当您插入Answer时,可以将此值用作参数。

This is an article如何做到这一点。

您还可以通过在insert-answer循环中取消对问题ID的查询来重构代码。相反,当您插入问题时,请为每个QuestionNo填充带有QuestionId的关联数组。在循环回答时,使用关联数组快速检索QuestionId。内存不应该是音乐会,因为您目前在HTTP请求中有所有问题和答案。

代码的核心将如下所示:

// AA: Declare an empty associative array for QuestionNo -> QuestionID
$question_ids = array()

for($i = 0;  $i < $c; $i++ )
{
        // AA: Extract the QuestionNo for multiple use
        $questionNo = $_POST['numQuestion'][$i];

        $insert->bind_param("ii", $sessionid, $questionNo);

        $insert->execute();

        if ($insert->errno)
        {
            // Handle query error here
            echo __LINE__.': '.$insert->error;
            break 1;
        }

        // AA: Retrieve the questionId from MySQL
        $questionId = mysql_insert_id();

        // AA: Add a key-value pair (QuestionNo, QuestionId) to $question_ids
        $question_ids[$questionNo] = $questionId;
}

$results = $_POST['value'];
foreach($results as $id => $value)
{
    $answer = $value;

    // AA: Look up the QuestionId for the question number
    $quesid = $question_ids[$id];

    foreach($value as $answer)
    {
        $insertanswer->bind_param("is", $quesid, $answer);

        $insertanswer->execute();

        if ($insertanswer->errno) {
            // Handle query error here
            echo __LINE__.': '.$insertanswer->error;
            break 3;
        }
    }
}

注意:我不是PHP程序员,我没有对此进行测试,因此可能存在语法错误。对不起:(

相关问题