2016-07-04 32 views
0

我具有以下表
評論表:
如何從兩個表中獲取特定數據?

id user_id question_id comment 
1  2  3   hii 

用戶表:

id u_name user_image 
2  naveen  a.jpg 
當question_id = 3被選擇如何打印這樣的值


user_image  u_name comment 
a.jpg   naveen  hii <br> 

sql查詢:

$sql = "SELECT u.user_image, u.name, c.comment 
FROM users u INNER JOIN comment c 
    ON u.id = c.user_id 
WHERE c.question_id = 2"; 

$result = mysqli_query($conn, $sql); 
if (mysqli_num_rows($result) > 0) { 
    // output data of each row 
while($rows = mysqli_fetch_assoc($result)) { 
echo '<td class="small">'.$rows['name'].'</td>'; 
echo '<td class="small">'.$rows['user_image'].'</td>'; 
echo '<td class="small">'.$rows['comment'].'</td>'; 

} 
} 
else { 
    echo "0 results"; 
} 

回答

0

使用的INNER JOIN

SELECT u.user_image, u.u_name, c.comment 
FROM users u INNER JOIN comments c 
    ON u.id = c.user_id 
WHERE c.question_id = 3 

SQLFiddle

+0

我得到錯誤:
「解析錯誤:語法錯誤,意想不到的 'U'(T_STRING)在C:\ XAMPP \ htdocs中\ n \ exam \ exam \ DOCS \ bindComment.php 16行' –

+0

@ user5789755您的PHP代碼中必須有錯誤,查詢應該在MySQL上正常工作。 –

+0

警告:mysqli_num_rows()期望參數1爲第22行中的C:\ xampp \ htdocs \ n \ exam \ exam \ DOCS \ bindComment.php中的mysqli_result,布爾值012,0結果 –