2013-07-15 34 views
2

我有一個正常的SQL語句,當我在MAMP上對其進行檢查時,它返回正確的結果。使用INNER JOIN打印mySQL查詢結果

SELECT `questions`.`questionID` AS question, `questions`.`questionText`, 
     `questions`.`categoryID`,`answers`.`answerID`,`answers`.`answerText`, 
     `answers`.`isTrue` 
FROM `questions`,`answers` 
WHERE `questions`.`questionID` = `answers`.`questionID` 

但我無法弄清楚如何用php打印輸出。請幫忙。這是代碼:

<html> 
<body> 

<?php 
    header('Content-Type: text/html; charset=utf-8'); 
    $con=mysqli_connect("localhost","root","root","Theory"); 
    // Check connection 
    if (mysqli_connect_errno()) 
    { 
     echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 
    $result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions` .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue` 
           FROM `questions`,`answers` 
           WHERE `questions`.`questionID` = `answers`.`questionID`"); 

    if (!$result) 
    { 
     die('Error: ' . mysqli_error($con)); 
    } 
    while($row = mysqli_fetch_array($result)) 
    { 
     echo "{"; 
     echo "{" . $row['questions'.'questionID'] . "}"; //this is not the full print 
     echo "{" . $row['questions'.'questionText'] . "}"; //just for chaking 
     echo "}"; 
    } 

    mysqli_close($con); 
    ?> 

</body> 
</head> 

我得到:「{{} {}} {{} {}} {{} {}} {{} {}} {{} {}} {{} { }} {{} {}} {{} {}}「迴應。

+1

打開,使用錯誤處理程序,然後再回來。另外,瞭解顯式的SQL語法。 – Kermit

+1

'if(!mysqli_query($ con,$ sql))' - >'if(!$ result)' –

+0

@FreshPrinceOfSO我只是一個初學者,所以我會欣賞一些參考。 – Luda

回答

6

你又在執行你的,如果條件中的查詢......但由於變量沒有被定義的$sql查詢爲空!

if (!mysqli_query($con,$sql))替換爲if (!$result),因爲您已經在上面的行中執行了查詢。

編輯來回答這個問題的評論:

,當你取生成的數組,你不需要指定表的別名只是列名或列的別名(如果存在)。

試試這個:錯誤報告

while($row = mysqli_fetch_array($result)) 
{ 
    echo "{"; 
    echo "{" . $row['questionID'] . "}"; //this is not the full print 
    echo "{" . $row['questionText'] . "}"; //just for checking 
    echo "}"; 
} 
+1

+ 1因爲你的評論比我的回答更快(我必須確保文檔中的返回值是FALSE)。 –

+1

@FranciscoPresencia +1對你也是因爲你的回答仍然是正確的。 –

5

$sql自然不設置。你可以這樣做:

$result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions` .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue` 
          FROM `questions`,`answers` 
          WHERE `questions`.`questionID` = `answers`.`questionID`"); 

if (!$result) 
{ 
    die('Error: ' . mysqli_error($con)); 
}