需要帮助在php中的两个不同数据库的两个不同表中插入数据

时间:2014-10-19 01:40:05

标签: php mysql database

我正在尝试同时连接两个不同的数据库,我使用过:

$connect1 = mysql_connect("localhost","root","");
mysql_select_db("database1", $connect1);
$res1 = mysql_query("query",$connect1);

$connect2 = mysql_connect("localhost","root","",true);
mysql_select_db("database2", $connect2);
$res2 = mysql_query("query",$connect2);  

建议https://stackoverflow.com/a/17788932/4157929

当我在两个数据库中更新两个表值时,这可以正常工作。但是,当我尝试INSERT到相同的两个数据库的相同的两个表时,我得到一个错误。该命令未被执行。我在下一个屏幕上获得第二个数据库的mySQL命令,即

0 - 

INSERT into products_description (products_id, language_id, products_name, products_description, products_url, products_viewed) VALUES ('12796', '1', 'COOKIES GINGERBREAD CHRISTMAS', 'COOKIES GINGERBREAD CHRISTMAS', '', '0')

[TEP STOP]

$ connect1和$ connect2是从一个包含在php中的application_top php文件处理的。因此,关闭第一个数据库并打开第二个数据库不是一个选项,因此我需要打开两个数据库连接。

我非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

尝试创建一个sql类(这是我用作基本sql引擎的东西)。看看这是否有助于插入:

<?php
    class   DBEngine
        {
            public  $con;
            public  $errors;
            public  function __construct($db = "database1",$host="localhost",$user="db_userName",$pass="mypassword")
                {
                    try {
                            $this->con  =   new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
                        }
                    catch (Exception $e) {
                          return 0;
                        }
                }

            // Simple fetch and return method
            public  function Fetch($_sql)
                {
                    $query  =   $this->con->prepare($_sql);
                    $query->execute();
                    $this->errors['fetch'][]    =   $query->errorInfo();

                    if($query->rowCount() > 0) {
                            while($rows = $query->fetch(PDO::FETCH_ASSOC)) {
                                    $array[]    =   $rows;
                                }
                        }

                    return (isset($array) && $array !== 0 && !empty($array))? $array: 0;
                }

            // Simple write to db method
            public  function Write($_sql)
                {
                    $query  =   $this->con->prepare($_sql);
                    $query->execute();
                    $this->errors['insert'][]   =   $query->errorInfo();
                }
        }

        $sql    =   "INSERT into products_description (products_id, language_id, products_name, products_description, products_url, products_viewed) VALUES ('12796', '1', 'COOKIES GINGERBREAD CHRISTMAS', 'COOKIES GINGERBREAD CHRISTMAS', '', '0')";

        // Insert 1
        $query1 =   new DBEngine();
        $query1->Write($sql);
        // Insert 2
        $query2 =   new DBEngine("database2");
        $query2->Write($sql); ?>
        <pre><?php
        print_r($query1->errors);
        print_r($query2->errors); ?>
        </pre>