两个数据库需要访问

时间:2012-01-22 23:36:31

标签: php mysql database join

我有两个数据库相同的服务器相同的域和相同的用户名和密码。我需要从主DB中选择,然后我需要能够连接到第二个DB并插入数据。

这是我正在尝试的,但它无法正常工作。

public function publish(){
        $result = mysql_query("SELECT * FROM customer_detail WHERE approvedforsite = 2");

        while($row = mysql_fetch_array($result))
        {
            echo $row['customer_id'] . " - " .$row['TradingName'] . " - " . $row['Phone'] . " - " . $row['Street'] . " - " . $row['City'] . " - " . $row['State'] . " - " . $row['PostCode'] . " - " .$row['Description'];
            echo "<br />";  

                mysql_query("INSERT INTO realcas_incard_server.approved_business (customer_id, tradingname) 
                VALUES ('". $row['customer_id'] ."','".$row['TradingName']."')");


                mysql_query("INSERT INTO realcas_incard_server.business_stores (customer_id, storeid, phone, street, suburb, state, postcode, description) 
                VALUES ('". $row['customer_id'] ."', 1, '".$row['Phone']."', '" .$row['Street'] . "', '" . $row['City'] . "', '" . $row['State'] . "', '" . $row['PostCode'] . "','".$row['Description']."')");

                $offerresult = mysql_query("SELECT * FROM  customer_realcash_offer WHERE businessid = ".$row['customer_id']);
                while($offers = mysql_fetch_array($offerresult))
                {
                    mysql_query("INSERT INTO _incard_server.Real_Cash_Offers (business_id,storeid,offer) VALUES (".$row['customer_id'].",1,'".$offers['offer']."')");   

                    echo $offers['offer']. "<br/>";
                }
            echo "<br />";
            echo "<br />";
        }
    }

2 个答案:

答案 0 :(得分:0)

您可以使用mysql_select_db()在同一服务器/用户名/密码/连接上的数据库之间切换,也可以使用database_name.table_name.column_name点缀语法(使用别名更容易,如{{1} }})。

这是你的两个选择。 (第三种选择是只使用一个数据库,但我认为这不是一个选项)

答案 1 :(得分:0)

说数据库首先

中有测试表格

测试 id int

数据库第二

中的

和表垃圾

垃圾 id int

然后

查询将是

插入垃圾邮件(id)(从first.test中选择ID);