php 如何在sql中编写查询连接两个不同的数据库表

jvidinwx  于 2023-01-19  发布在  PHP
关注(0)|答案(1)|浏览(157)

我有学校的项目,建立电子商务,经过一些研究,我发现创建不同的数据库的产品形象是很好的做法,但在这里,我面临的形象,以连接两个不同的表的所有表。我有两个不同的数据库类名。

  • 1. $db = Database::newInstance();
  • 2. $dtb = Idatabase::newInstance();

1. $db = Database::newInstance();这具有表名products具有列puidproducts_attribute_01具有列puidproducts_inventory具有列puid
2.$dtb = Idatabase::newInstance();它具有表名pd_images和列puid

如何连接所有表

这是我正在尝试的,但给出错误Fatal error: Uncaught Error: Object of class Database could not be converted to string in 18

$db = Database::newInstance();
$dbname1 = $db->getDbName();
$dtb = Idatabase::newInstance();
$dbname2 = $dtb->getDb_Name();
$data = array();
$sql = "SELECT *
FROM $dbname1.products
INNER JOIN $dbname1.products_attribute_01 ON products.puid = products_attribute_01.puid
INNER JOIN $dbname1.products_inventory ON products.puid = products_inventory.puid
UNION ALL
SELECT *
FROM $dbname2.images.pd_images";
$row1 = $db->read($sql, $data);
var_dump($row1); 
$data['row1'] = $row1;

这里是数据库

Class Database{
    //This is Database class
    public static $conn;

    public function __construct(){

        try {

            $string = DB_TYPE.":host=".DB_HOST.";dbname=".DB_NAME;
            self::$conn = new PDO($string,DB_USER,DB_PASS);

        } catch (PDOException $e) {
            die($e->getMessage());
        }

    }
    public static function getDbName(){
        return DB_NAME;
        }
    public static function getInstance(){

        if (self::$conn) {
           return self::$conn; 
        }
        return $instance = new self();
    }
    public static function newInstance(){
        return $instance = new self();
    }
    //read from database
    public function read($query,$data = array()) {
        
        $statement = self::$conn->prepare($query);
        $result = $statement->execute($data);

        if ($result) {
            $data = $statement->fetchAll(PDO::FETCH_OBJ);
            if (is_array($data) && count($data) > 0) {
                return $data;
            }
        }
        
        return false;
    }
    //write from database
    public function write($query,$data = array()){

        $statement = self::$conn->prepare($query);
        $result = $statement->execute($data);

        if ($result) {
            
            return true;
        }
        return false;
    }

}

我现在已添加此内容

public static function getDbName(){
return DB_NAME;
}
s5a0g9ez

s5a0g9ez1#

这样做(成功工作),请批准它不会给予任何麻烦,在未来的黑客或任何方面?

$db = Database::newInstance();
$dtb = Idatabase::newInstance();
$dbName1 = $db->getDbName();
$dbName2 = $dtb->getDb_Name();
$data = array();
$sql = "SELECT *
FROM $dbName1.products
INNER JOIN $dbName1.products_attribute_01 ON products.puid = products_attribute_01.puid
INNER JOIN $dbName1.products_inventory ON products.puid = products_inventory.puid
INNER JOIN $dbName2.pd_images ON products.puid = pd_images.puid";
$result = $db->read($sql, $data);

相关问题