[英]Select more than one row with same value in one column in mysql?
我正在嘗試使用PHP和MySQL創建注釋系統。 我制作了一個名為“ comment”的表,用於存儲詳細信息
id | date |product_id | user_name | email_id | comment | | | | | 1 |2013-05-07 | 10001 | jabong | jabong@jabong.com | this is good product 2 |2013-05-07 | 10001 | john | john@gmail.com | I bought this product
等等
現在,我要選擇並打印所有具有product_id = 10001的行。 我正在使用以下代碼來打印詳細信息
$comment="";
$id=$_GET['id'];//this is the product_id which is taken from URL
$query=mysql_query("SELECT * FROM comment WHERE product_id='$id'");
while($data = mysql_fetch_array($query))
{
$name = $data["user_name"];
$email = $data["email_id"];
$comment = $data["comment"];
$date=strftime("%d %b, %Y", strtotime($data["date"]));
$comment.='<table>
<tr>
<td>Date: '.$date.'</td>
</tr>
<tr>
<td>Name: '.$name.'</td>
</tr>
<tr>
<td>Email_id: '.$email.'</td>
</tr>
<tr>
<td>Product Review: '.$comment.'</td>
</tr>
</table><hr />';
然后在正文部分中回顯它們。 但我只得到一個結果。 因此,請幫助我獲取正確的代碼。
我的代碼有一個小問題。 我兩次使用相同的變量,也沒有使用連接符號。 但是現在解決了-
$review="";
if (isset($_GET['id']))
{
$id=mysql_real_escape_string(trim($_GET['id']));
$query=mysql_query("SELECT * FROM comment WHERE product_id='$id'");
$review.='<table width="70%" cellpadding="6px" cellspacing="0" >';
while($data=mysql_fetch_array($query))
{
$name = $data["user_name"];
$email = $data["email_id"];
$comment = $data["comment"];
$date=strftime("%d %b, %Y", strtotime($data["date"]));
$review.='<tr>
<td>
<table width="100%" border="0" style="border:1px solid; border-color:#05fdee; background-color:#e4f2f1;">
<tr>
<td rowspan="2" width="100px"> <img src="profile.png" /> </td>
<td align="left"><b> '.$name.' </b> says -</td>
<td align="right"><b> '.$date.' </b></td>
</tr>
<tr>
<td colspan="2">'.$comment.'</td>
</tr>
</table>
</td>
</tr>';
}// while loop ends here
$review.='</table>';
}
首先,清理數據。
$id=mysql_real_escape_string(trim($_GET['id']));
$query=mysql_query("SELECT * FROM comment WHERE product_id='$id'");
while($ data = mysql_fetch_array($ query))
第二個問題是您在每個循環中都覆蓋了$ comment變量,因此即使循環兩次,您也只會得到1條記錄。
remove this: $comment = $data["comment"];
change this: <td>Product Review: '.$comment.'</td>
to this: <td>Product Review: '.$data["comment"].'</td>
你有這行:
$comment = $data["comment"];
這覆蓋了這個:
$comment.='<table>
<tr>
<td>Date: '.$date.'</td>
</tr>
<tr>
<td>Name: '.$name.'</td>
</tr>
<tr>
<td>Email_id: '.$email.'</td>
</tr>
<tr>
<td>Product Review: '.$comment.'</td>
</tr>
</table><hr />';
因此,當您在執行echo $comment
它會顯示最后一個。
更改變量並完成
就像是:
$comment_sql = $data["comment"];
....
$comment.='<table>
<tr>
<td>Date: '.$date.'</td>
</tr>
<tr>
<td>Name: '.$name.'</td>
</tr>
<tr>
<td>Email_id: '.$email.'</td>
</tr>
<tr>
<td>Product Review: '.$comment_sql.'</td>
</tr>
</table><hr />';
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.