Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

php - Joining Tables from different Database

I am trying to fetch data from two tables in two different database in a same server. I am using this code

<?php

    $host='localhost';
    $root='root';
    $password='mypass';
    $db=mysql_connect($host,$root,$password) or die('unable to connect database');
    $dbname='BUSMSTR_10';
    mysql_select_db($dbname,$db) or die(mysql_error($db));

    $db2=mysql_connect($host,$root,$password) or die('unable to connect database');
    $dbname='BULIB_Info';
    mysql_select_db($dbname,$db2) or die(mysql_error($db2));

    $sql="SELECT 
        m_Student.Stud_Name_Form AS Stud_Name_Form,
        m_Student.Enrl_no AS Enrl_no,
        m_Subject.Sub_name AS Sub_name
    FROM 
        BUSMSTR_05.m_Student m_Student
    INNER JOIN
        BULIB_Info.m_Subject m_Subject
    ON
        m_Student.Sub_ID=m_Subject.Sub_ID

    LIMIT 10";

$rs=mysql_query($sql);

    while($row=mysql_fetch_assoc($rs)){
        echo $row['Stud_Name_Form']."|||||".$row['Enrl_no']."|||||".$row['Sub_name']."<BR>";
        }

?>

But I am getting error. whats wrong with it.... and how will I fix this??

Error msg----

Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/budcc/html/student/PHP/Student.php  on line 25
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's really not difficult to join seperate databases (assuming they reside on the same server) Just like you would specify fields using the "table.field", you can also use "database.table.field" Below is an example of a two database join:

$sql="SELECT db1.table1.somefield, db2.table1.somefield FROM db1.table1 INNER JOIN db2.table1 ON db1.table1.someid = db2.table1.someid WHERE db1.table1.somefield = 'queryCrit';"

You simply write you query just like you would if you were working in one db, just use the dot notation to specify your databases as well.

As far as your problem goes i dont think you are adding database names before tables names everywhere.Try that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...