使用mysqli预处理语句时不能使用prepare()

时间:2013-06-28 22:18:10

标签: php oop mysqli prepared-statement

我尝试创建面向对象的方法来处理我正在努力工作的项目,但是我无法理解数据库类的想法。我收到以下错误。

    Call to undefined method Database::prepare()

数据库类

class Database
{

    protected $connection;

    function __construct()
    {
        $this->createConnection();
    }

    private function createConnection()
    {

        $this->connection = new mysqli("localhost", "user", "password", "test");
        if ($this->connection->connect_errno)
        {
            echo "Failed to connect to MySQL: (" . $this->connection->connect_errno . ") " . $this->connection->connect_error;
        }
        else
        {
            echo 'Connected to database.<br />';
        }

    }
}

$db = new Database();

UserActions类

class userActions
{

    protected $_db;
    protected $_username;
    protected $_password;
    protected $_auth;
    protected $tableName;
    function __construct($db, $username, $password, $auth)
    {
        $this->_db = $db;
        $this->_username = $username;
        $this->_password = $password;
        $this->_auth = $auth;

        $this->checkUserExists();
    }

    private function checkUserExists()
    {
        $query= "SELECT COUNT(*) FROM '{$this->tableName}' WHERE username = ?";
        $stmt = $this->_db->prepare($query);
        $stmt->bind_param('s', $this->username);
        $userNumber= $stmt->execute();
        echo $userNumber;
    }
}

我做错了什么,我可以采取任何措施来改善我执行此任务的方式吗?

1 个答案:

答案 0 :(得分:1)

您需要在课程中添加以下方法:

public function prepare($query) {
  return $this->connection->prepare($query);
}

您可以为您的类定义一个魔术方法,自动将任何未定义的方法传递给连接:

public function __call($name, $arguments) {
  return call_user_func_array(array($this->connection, $name), $arguments);
}