php - OOP PHP undefined variable 和空查询

标签 php mysql oop undefined

我正在尝试通过查询测试数据库来学习 OOP PHP。我尝试用谷歌搜索答案,但没有成功。这是我的代码:

<?php

class DB {

        protected $db;
        protected $query;

        public function __construct() {
            $this->db = new mysqli("localhost","root","","test2");
            $this->query = "SELECT * FROM test";
        }


        public function querydb() {
            $this->db->query($db,$query);
        }

    }

    $database = new DB();
    $database->querydb();


?>

它表示构造函数中定义的两个变量未定义,并且查询为空。有什么建议吗?

最佳答案

更改:

$this->db->query($db,$query);

致:

$this->db->query($this->query);

试试这个:

<?php

class DB {

        protected $db;
        protected $query;

        public function __construct() {
            $this->db = new mysqli("localhost","root","","test2");
            $this->query = "SELECT * FROM test";
        }


        public function querydb() {
            $this->db->query($this->query);
        }

    }

    $database = new DB();
    $database->querydb();


?>

关于php - OOP PHP undefined variable 和空查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24863955/

相关文章:

如果未选中复选框,PHP 会更新数据库

java - Android 数据库连接

mysql - (数据库设计,mysql)我的数据库设计适合基本的购物车吗?(我是数据库设计的新手)

MySQL SELECT table.column AS 表

java - 我什么时候应该将代码分成单独的类?

c# - 类字段可以密封吗?

php - 使用 jQuery POST 发送多个 <select> 元素

mysql - TRIM 字符串连接值

python - 克服 Python 在实例方法方面的局限性

php - 在文本框中显示值以使用 ajax 和 php 进行编辑