简体   繁体   English

为什么我无法在php mysql中显示我的记录?

[英]why i can't display my records in php mysql?

I have records in my database but I can't display them. 我的数据库中有记录,但无法显示。 Can someone check my codes, please. 有人可以检查我的密码吗? I'm just an amateur web developer. 我只是一个业余Web开发人员。 Thanks for any help. 谢谢你的帮助。

<?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>";
}
?>

With this code I get the else result which is Error . 使用此代码,我得到else结果为Error If I remove WHERE group='$g_id' from the query, all of my records are displayed randomly, but I'd like to show my records (members) by group. 如果我从查询中删除WHERE group='$g_id' ,我的所有记录将随机显示,但我想按组显示我的记录(成员)。

You need to escape reserved words in MySQL like group with backticks 您需要在MySQL中转义保留字,例如带反引号的group

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 . 另外,请不要在新代码中使用mysql_ *函数 They are no longer maintained and are officially deprecated . 它们不再维护,已正式弃用 Learn about Prepared Statements instead, and use PDO or MySQLi . 而是了解有关预准备语句的信息 ,并使用PDOMySQLi See this article for a quick overview how to do it and why it is so important. 请参阅本文 ,以快速了解如何做以及为什么它如此重要。

Try like 尝试像

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

or simply 或简单地

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

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>";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM