2013-01-05 3 views
3

질문 :외래 키가 생성되지 않는

가 (이 쿼리를해야합니다) 아래 선택 쿼리를 수행 할 :

SELECT QuestionId 질문 FROM WHERE (QuestionNo = 및 세션 ID = ?)

Question 테이블에서 QuestionId를 찾을 수 있으려면 이 답변 테이블에 저장되어 모든 답변에 대해 이 답변을 결정할 수 있습니다. ERS는 질문에 속해

문제 :

mysqli 코드의 문제가 올바른 QuestionId 값을 삽입 할 수없는 것입니다. Answer 테이블에 QuestionId가 0으로 표시됩니다. 올바른 QuestionId를 표시 할 수 있도록 누군가가이를 수정할 수 있습니까?

맨 위에 제공된 SELECT 쿼리를 수행해야합니다. 나는 그것을 mysqli에서 사용해야한다. 순간

질문 표

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

응답 테이블 : : 아래

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

:

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

어떤 대답 표과 같아야 여기

는 DB의 테이블입니다 는 코드 :

직접 삽입 한 후 질문에 autoincrementing ID로 사용되는 시퀀스의 마지막 값을 검색 할 필요가
$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(); 
} 

?> 
+0

어떤 데이터베이스를 사용하고 있습니까? 어떤 오류가 있습니까? – Oded

+0

"작성되지 않았습니다"라는 의미는 무엇입니까? –

+0

올바른 데이터베이스에 외래 키를 만들고 테스트하지 않았습니까? 또는 개발 데이터베이스? –

답변

1

- LAST_INSERT_ID() SQL 함수를 사용하여이 작업을 수행. 그런 다음 Answer에 삽입 할 때이 값을 매개 변수로 사용할 수 있습니다.

This is an article이 작업을 수행하는 방법에 대해 설명합니다.

삽입 - 응답 루프에서 질문 ID에 대한 쿼리를 제거하여 코드를 재구성 할 수도 있습니다. 대신 질문을 삽입 할 때 각 QuestionNo에 대한 QuestionId로 연관 배열을 채 웁니다. 답변을 반복하면서 연관 배열을 사용하여 QuestionId를 빠르게 검색 할 수 있습니다. 현재 HTTP 요청에서 모든 질문과 답변을 가지고 있으므로 메모리가 콘서트가 아니어야합니다. 나는 PHP 프로그래머가 아니에요, 나는이 테스트를하지 않은, 그래서 구문 오류가있을 수 있습니다 :

// 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; 
     } 
    } 
} 

참고 :

코드의 핵심은 다음과 같이 표시됩니다. 죄송합니다 : (

+0

제공된 선택 쿼리로 수행 할 수 있어야합니다. 내 문제는 코드를 어디에 배치해야 하는지를 아는 것이다. LAST_INSERT_ID()를 사용하여 코드를 배치해야하는 위치를 표시 할 수 있다면 좋을 것입니다. 나는 그 전에 그걸 시험해 봤지만 그 일로 큰 어려움을 겪고있었습니다. 제게 큰 문제가 있기 때문에 시간을 알려주시겠습니까? – Manixman

+0

@Manixman : 코드 –

+0

로 답변을 업데이트 해 주셔서 대단히 감사합니다. 그것이 나에게 현상금을 수여 할 것입니다. 나는 그때까지 너에게 줄 것이다 20 시간 : – Manixman

관련 문제