我正在开发一个离线聊天应用程序,我有两个表1.用户详细信息(cli_id,电子邮件,用户名)2。聊天表(c_from,c_to,subject,matter,image)现在的问题是我我从用户表中获取cli_id作为from和to,但是在获取查询时它返回一行,我的代码看起来像这样
<table width="100%" border="0">
<tr>
<td width="16%"><strong>From</strong></td>
<td width="23%"><strong>Subject</strong></td>
<td width="40%"><strong>Matter</strong></td>
<td width="21%"><strong>To</strong></td>
</tr>
<?php
include('connect.php');
$sql=mysql_query("SELECT * FROM `chat` ORDER BY chat_id DESC")or die(mysql_error());
while($row=mysql_fetch_array($sql))
{
?>
<tr>
<td><?php echo $row['c_from']; ?></td>
<td><a href="read_chat.php?id=<?php echo $row['chat_id']; ?>"><?php echo $row['subject']; ?></a></td>
<td><a href="read_chat.php?id=<?php echo $row['chat_id']; ?>"><?php echo $row['matter']; ?></a></td>
<td><?php
$chat_to =$row['c_to'];
$sql=mysql_query("SELECT * FROM `client` WHERE cli_id = $chat_to")or die(mysql_error());
while($qry=mysql_fetch_array($sql))
{
echo $qry['email'];
}
?></td>
</tr>
<?php } ?>
</table>
答案 0 :(得分:1)
你在循环中覆盖$sql
,它用一个结果集替换外循环中的结果集,该结果集在代码执行返回外循环时已经被“清空”。
答案 1 :(得分:0)
$ sql变量在while循环中发生了变化。在这里使用不同的变量:
$sql=mysql_query("SELECT * FROM `client` WHERE cli_id = $chat_to")or die(mysql_error());
答案 2 :(得分:0)
试试这个:
<table width="100%" border="0">
<tr>
<td width="16%"><strong>From</strong></td>
<td width="23%"><strong>Subject</strong></td>
<td width="40%"><strong>Matter</strong></td>
<td width="21%"><strong>To</strong></td>
</tr>
<?php
include('connect.php');
$selectChat=mysql_query("SELECT * FROM `chat` ORDER BY chat_id DESC")or die(mysql_error());
while($row=mysql_fetch_array($selectChat))
{
?>
<tr>
<td><?php echo $row['c_from']; ?></td>
<td><a href="read_chat.php?id=<?php echo $row['chat_id']; ?>"><?php echo $row['subject']; ?></a></td>
<td><a href="read_chat.php?id=<?php echo $row['chat_id']; ?>"><?php echo $row['matter']; ?></a></td>
<td><?php
$chat_to =$row['c_to'];
$selectClient=mysql_query("SELECT * FROM `client` WHERE cli_id = $chat_to")or die(mysql_error());
while($qry=mysql_fetch_array($selectClient))
{
echo $qry['email'];
}
?></td>
</tr>
<?php } ?>
</table>
答案 3 :(得分:0)
为了最大限度地减少数据库请求的数量,最好使用连接,这样也可以减少在第一个循环中有第二个查询循环的需要。请尝试以下代码
<table width="100%" border="0">
<tr>
<td width="16%"><strong>From</strong></td>
<td width="23%"><strong>Subject</strong></td>
<td width="40%"><strong>Matter</strong></td>
<td width="21%"><strong>To</strong></td>
</tr>
<?php
include('connect.php');
$sql=mysql_query("SELECT * FROM `chat` LEFT JOIN 'client' on 'chat.c_to = client.cli_id' ORDER BY chat_id DESC")or die(mysql_error());
while($row=mysql_fetch_array($sql))
{
?>
<tr>
<td><?php echo $row['c_from']; ?></td>
<td><a href="read_chat.php?id=<?php echo $row['chat_id']; ?>"><?php echo $row['subject']; ?></a> </td>
<td><a href="read_chat.php?id=<?php echo $row['chat_id']; ?>"><?php echo $row['matter']; ?></a></td>
<td><?php echo $row['email'];?></td>
</tr>
<?php } ?>
</table>
答案 4 :(得分:-2)
您必须重写主查询后立即出现的while语句
while($row=mysql_fetch_array($sql))
as
while($row=mysql_fetch_row($sql))
希望这对你有所帮助。