Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Can';在使用mysqli prepared语句时不要使用prepare()_Php_Oop_Mysqli_Prepared Statement - Fatal编程技术网

Php Can';在使用mysqli prepared语句时不要使用prepare()

Php Can';在使用mysqli prepared语句时不要使用prepare(),php,oop,mysqli,prepared-statement,Php,Oop,Mysqli,Prepared Statement,我正试图为一个有趣的项目创建一种面向对象的方法,但我很难理解数据库类的概念。我得到以下错误 Call to undefined method Database::prepare() 数据库类 class userActions { protected $_db; protected $_username; protected $_password; protected $_auth; protected $tableName; func

我正试图为一个有趣的项目创建一种面向对象的方法,但我很难理解数据库类的概念。我得到以下错误

    Call to undefined method Database::prepare()
数据库类

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;
    }
}

我做错了什么,我能做些什么来改进我完成这项任务的方式吗?

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

public function prepare($query) {
  return $this->connection->prepare($query);
}
您可以为类定义一个神奇的方法,该方法自动将任何未定义的方法传递给连接:

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

您的数据库类没有准备例程,不确定您还期望什么…@crowder,但您(我假设)正在这里传入您的数据库类(如果没有,为什么要共享该代码)?您似乎期望您的类扩展
mysqli
类。但是它只是将一个
mysqli
对象存储为一个私有变量。谢谢你的回答:)但是它似乎有点冗长,我这样编码对吗?还是有更好的方法来编码类?我添加了一个通用的
\u call()
方法,允许您将类用作
mysqli
的代理。或者,您可以定义一个返回连接的公共方法,然后直接在该连接上调用mysqli方法。我认为第二个选项是最好的,因为我现在遇到了必须访问“bind_param”的问题。现在还不清楚您的类的意义是什么。为什么不直接调用
mysqli\u connect()
?类所做的唯一事情就是隐藏连接参数。
public function __call($name, $arguments) {
  return call_user_func_array(array($this->connection, $name), $arguments);
}