连接注入故障排除

时间:2013-08-23 13:12:42

标签: php

正如所建议的那样,我正在尝试使用连接注入技术来允许我的主类操作。注入代码来自另一个文件的类。见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

有人能够看看我做了什么,并具体指出我做错了什么,以及如何纠正脚本以使其运作。

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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();
相关问题