2

正如建议的那样,我正在尝试使用连接注入技术来允许我的主类运行。注入代码来自另一个文件上的类。参见connection.php中的图A

class qcon{

public static $conn;

function dbcon()
{


     if (empty($conn)) 
     {
         $host = 'x';
         $username = 'x';
         $password = 'x';
         $dbname = 'x';
         $conn = mysqli_connect($host , $username  , $password ,$dbname) or die("Oops! Please check SQL connection settings");
     }

     return $conn;
}

}

在这里,我有我的类注入代码,它是我的主类中的一个方法。参见图 B 上的 class.php

    class dbcats {
    var $conn;
    public function __construct(qcon $dbcon)
    {
        $this->conn = $dbcon;
    }

function getResult(){

            $result = mysqli_query($this->conn , "SELECT * from member" ); // Error see end of question
            if ($result) {
                return $result;
            } 
            else {
                die("SQL Retrieve Error: " . mysqli_error($this->conn));
            }
        }
}

最后,请参阅图 C 了解我在网页中拨打的电话。

$db1 = new qcon();
$db1->dbcon();
$helper = new dbevent($db1);
$result = $helper->getResult();

以上导致以下情况

Warning: mysqli_query() expects parameter 1 to be mysqli, object given in C:\xxxxxxxxxxxxxx\webpage.php on line 35

是否有人能够查看我所做的并具体指出我做错了什么,以及如何更正脚本以使其运行。

4

2 回答 2

2

你不照顾退货$conn

$db1 = new qcon();
$db1->dbcon();//This line returns the connection
$helper = new dbevent($db1);
$result = $helper->getResult();

应该是这样的。

$db1 = new qcon();
$conn = $db1->dbcon();
$helper = new dbevent($conn);
$result = $helper->getResult();
于 2013-08-23T13:19:21.473 回答
2

您的代码有很多问题,这里是修改后的代码(请自行查找差异)

 class Qcon
 {

    public static $conn;

    public static function connection()
    {

        if (empty(self::$conn)) {
            $host = 'x';
            $username = 'x';
            $password = 'x';
            $dbname = 'x';
            self::$conn = mysqli_connect($host, $username, $password, $dbname) or die("Oops! Please check SQL connection settings");
        }

        return self::$conn;
    }
}

进而:

$helper = new dbevent(Qcon::connection());
$result = $helper->getResult();
于 2013-08-23T13:23:22.753 回答