多个mysql查询成一个php二维数组 [英] multiple mysql queries into one php two-dimensional array

查看:285
本文介绍了多个mysql查询成一个php二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构代码,遇到了麻烦。以下代码中的第一个查询获取最新提交的选项卡的tab_id。第二个查询获取每个选项卡的详细信息。
用我以前的方式,我嵌入了php和html,这确实是一团糟。现在,我想将2个查询合并为1个查询和/或将其加载到数组中。

I'm refactoring my code and just hit a snag. The first query in the code below gets the tab_id of the latest submitted tabs. The second Query gets the detail of each tab. In my old way of doing it, i embedded php and html and it was truly an utter mess. Right now I'd like to merge the 2 queries into 1 and/or load it into an array.

随意提问和/或屠夫

function get_newest_tabs()
{
    $db_open;
    $sql = "SELECT tab_id, song_id, user_id FROM tabs ORDER BY time_added DESC ". "LIMIT 15";
    $result = mysql_query($sql) or die("ERROR - newest tabs function: ".mysql_error());

    if (mysql_num_rows($result) > 0)
    {
        for($i = 0; $i < mysql_num_rows($result); $i++)
        {
            $tab_id = mysql_result($result, $i, "tab_id");
            $db_open;
            $sql =  
                "SELECT tabs.tab_id, tabs.tab_version, tabs.number_of_hits, artist.artist_name, users.user_alias, songs.song_name, tabs.time_added
                FROM tabs, users, artist, songs
                WHERE tabs.tab_id ='".$tab_id."'  AND tabs.user_id = users.user_id AND tabs.song_id = songs.song_id AND songs.artist_id = artist.artist_id";
            $result2 = mysql_query($sql) or die("ERROR - i3p mysql - 4: ".mysql_error());

            if(mysql_num_rows($result2) == 1)
            {
                $song_name = mysql_result($result2, 0, "songs.song_name");
                $artist_name = mysql_result($result2, 0, "artist.artist_name");
                $user_alias = mysql_result($result2, 0, "users.user_alias");
                $tab_version = mysql_result($result2, 0, "tabs.tab_version");
                $number_of_hits = mysql_result($result2, 0, "tabs.number_of_hits");
                $time_added = mysql_result($result2, 0, "tabs.time_added");

            }
        }
    }
}


推荐答案

我建议使用JOIN而不是从多个表中进行选择。您也可以加入tabs表。

I'd suggest using JOIN instead of selecting from multiple tables. You can also join the tabs table.

SELECT tabs.tab_id, tabs.song_id, tabs.user_id, tabs.tab_version, tabs.number_of_hits, artist.artist_name, users.user_alias, songs.song_name, tabs.time_added
FROM tabs
LEFT JOIN users ON users.user_id = tabs.user_id
LEFT JOIN songs ON songs.song_id = tabs.song_id
LEFT JOIN artist ON artist.artist_id = songs.artist_id
ORDER BY tabs.time_added DESC LIMIT 15

然后您可以执行如下循环:

Then you could do a loop like:

while($row = mysql_fetch_array($result)) {
$tabs[$row['tab_id']] = $row;
}

只要每个标签上有一位用户/歌曲/歌手您的数据数组。

As long as you have one user/song/artist per tab that will get you an array of your data.

这篇关于多个mysql查询成一个php二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆