mysqli_prepare()期望参数1为mysqli,给定对象

时间:2014-11-11 11:57:07

标签: php mysql mysqli

好的。所以基本上。这是我的代码。

的login.php

require_once("./libs/db_cxn.php");

    $cxn = new newConnection();

    $stmt = "SELECT users.username FROM users WHERE username=$username AND password=MD5($password)";
    $qry = \mysqli_prepare($cxn, $stmt);
    $res = mysqli_execute($qry);

db_cxn.php

class newConnection{

    function __construct(){
        $conf = array(
            "host" => "localhost",
            "username" => "root", 
            "password" => "root",
            "dbname" => "db_BookWorm",
            "port" => ini_get("mysqli.default_port"),
            "socket" => ini_get("mysqli.default_socket"),
            "prefix" => "bWorm_"
        );
        $cxn = new mysqli($conf["host"], $conf["username"], $conf["password"], $conf["dbname"]);

        if ($cxn->connect_errno){
            \printf("Connection failed: %s\n", $cxn->connect_error);
            exit();
        }
    }

    function _destruct(){
        mysqli_close($this);
    }
}

我有错误报告,每当我尝试运行该代码时都会给出以下错误消息

Warning: mysqli_prepare() expects parameter 1 to be mysqli, object given in \\MORIARTY\HOME\15\5CBA2901\Desktop\comp_proj\project\www\login.php on line 34

有关如何解决此问题的任何线索?我已经创建了这个连接类,因为我将打开连接的频率,并认为它节省了我的时间和悲伤。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

<?php

/**
  change your code like that :
  ---------------------
  for db_cxn.php file
  ---------------------
 * */
class newConnection {

    static $cxn;

    function __construct() {
        $conf = array(
            "host" => "localhost",
            "username" => "root",
            "password" => "",
            "dbname" => "test",
            "port" => ini_get("mysqli.default_port"),
            "socket" => ini_get("mysqli.default_socket"),
            "prefix" => ""
        );
        self::$cxn = mysqli_connect($conf["host"], $conf["username"], $conf["password"], $conf["dbname"]);

        if (self::$cxn->connect_errno) {
            \printf("Connection failed: %s\n", self::$cxn->connect_error);
            exit();
        }
    }

    function getConnection() {
        return self::$cxn;
    }

    function _destruct() {
        mysqli_close($this);
    }

}

答案 1 :(得分:0)

<?php

/* * *
  ----------------
  for login.php
  ----------------
 */
require_once("./libs/db_cxn.php");

$obj = new newConnection();
$cxn = $obj->getConnection();
$id = 1;
$stmt = "SELECT users.username FROM users WHERE username=$username AND password=MD5($password)";
$qry = mysqli_prepare($cxn, $stmt);
$res = mysqli_execute($qry);