0

我的数据库中有记录,但我无法显示它们。有人可以检查我的代码,请。我只是一个业余的网络开发人员。谢谢你的帮助。

<?php
$groups=mysql_query("SELECT * FROM groups ORDER BY id ASC");
$g_res=mysql_affected_rows();
if($g_res>0)
{
while($row=mysql_fetch_array($groups))
{
    $g_id=$row['id'];
    $g_name=$row['g_name'];

    $members=mysql_query("SELECT * FROM members WHERE group='$g_id'");
    $m_res=mysql_affected_rows();
    if($m_res>0)
    {
        while($row2=mysql_fetch_array($members))
        {
            $m_id=$row2['id'];
            $m_name=$row2['m_name'];
            $m_email=$row2['m_email'];
            echo "<tr><td>$m_name<br/>($g_name)</td><td>$m_email</td></tr>";
        }
    }
    else
    {
    echo "<tr><td colspan=2>Nothing to display</td></tr>";
    }
}
}
else
{
echo "<tr><td colspan=2>Error</td></tr>";
}
?>

使用此代码,我得到的else结果是Error. 如果我WHERE group='$g_id'从查询中删除,我的所有记录都会随机显示,但我想按组显示我的记录(成员)。

4

3 回答 3

3

You need to escape reserved words in MySQL like group with backticks

SELECT * FROM members WHERE `group` = '$g_id'
                            ^-----^-------------here

You can also spare the inner loop when you join your data like this

select g.id as gid, g.g_name, m.id as mid, m.m_name, m.m_email
from groups g
inner join members m on g.id = m.group
order by g.id asc

This is easier and will increase performance since you don't need to execute a lot of queries but just one.

Also please don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. Learn about Prepared Statements instead, and use PDO or MySQLi. See this article for a quick overview how to do it and why it is so important.

于 2013-06-24T11:55:36.023 回答
0

Try like

$members=mysql_query("SELECT * FROM members WHERE `group` = '".$g_id."');

or simply

$members=mysql_query("SELECT * FROM members WHERE `group` = '$g_id'");
于 2013-06-24T11:55:48.147 回答
0

You have to concatenate your variables. Try this:

$members=mysql_query("SELECT * FROM members WHERE `group`='".$g_id."'");

And

echo "<tr><td>".$m_name."<br/>(".$g_name.")</td><td>".$m_email."</td></tr>";

于 2013-06-24T11:56:02.783 回答