dongshenghe1833 2013-06-28 22:18
浏览 106
已采纳

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

I'm tryign to create an object orientated approach to a project I'm working on for fun, but I'm having trouble getting my head around the idea of a database class. I'm getting the following error.

    Call to undefined method Database::prepare()

Database Class

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

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

What am I doing wrong, could I do anything to improve the way I'm going about this task?

  • 写回答

1条回答 默认 最新

  • doujiu1447 2013-06-28 22:25
    关注

    You need to add the following method to your class:

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

    You could define a magic method for your class that automatically passes any undefined method to the connection:

    public function __call($name, $arguments) {
      return call_user_func_array(array($this->connection, $name), $arguments);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线