doudi5524 2015-01-19 10:37
浏览 34
已采纳

如何显示来自2个不同数据库的数据

I have an hard time to retrieve data in a table from MySQL database. I have 2 different database that cannot be merge but there is a table in the first database that is identical to the second database.

Description Database 1 table: areas : ar_id, name, password.
Description Database 2 table: user : id, username, pass.

Now, When the user Login, He logs in the 2nd database. in each page of the user I have use $_SESSION['username'] to call the username.

Importantly, In every page, I have table that displays data from different tables using the username in the 2 Database; this else the SQL to be specific and only provide each user with their own information. and That's Ok. This is the SQL:

SELECT Client_table.Name, Client_table.Client_Id FROM Client_table, user WHERE user.username = '" . $_SESSION['username'] . "' AND Client_table.Branch = user.area Order by Name ASC

In one of the page, I totally using the 1st Database with this SQL to display data in the table :

select site_id, site_name from sites WHERE srep_id = 5
                        AND status = 1 or status = 2
                        order by site_name asc 

QUESTION: I would like to display this SQL data in a table by using the username or id from the 2nd database BUT is returns Empty Table (I include both Database in this page). This is my current SQL but still not displaying anything:

SELECT cl.client_name, st.site_id, st.site_name
                FROM Database1.sites st
                JOIN Database2.user u ON u.id = st.ar_id
                JOIN Database1.clients cl ON cl.client_id = st.client_id
WHERE Database1.st.name = '".$_SESSION['username']."'
                        AND st.status > 0
                        ORDER BY st.site_name ASC

NOTE: This is a major problem that took me almost a week! Please some one help!

  • 写回答

1条回答 默认 最新

  • doujia3441 2015-01-20 06:55
    关注

    I think I have an answer. After browsing and doing some search, I sound that I can make use of the $_SESSION here and Also, This was my final SQL Statement that Helped me to Connect the 2 Database from the same SQL Statement by using variable in PHP Script.

    session_start();

    $result = mysql_query("SELECT cl.client_name, st.site_id, st.site_name, ar.rep_id
                            FROM sites st
                            JOIN areas ar ON ar.rep_id = st.srep_id
                            JOIN clients cl ON cl.client_id = st.client_id
                            WHERE st.srep_id = '".$_SESSION['userarea']."'
                            AND st.status > 0
                            ORDER BY st.site_name ASC");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?