将变量传递给mysql查询导致"函数查询null"

时间:2017-05-16 14:37:05

标签: php mysql

我有一个我要传递查询的类,但是致命错误

  

函数查询null'

尝试运行查询时发生

我回复了$ mysql_statement并得到了

select * from users 

这是预期的查询,但在查询语句的上下文中,它一直告诉返回致命错误function query on null

为什么"选择*来自用户"合法存储在$mysql_statement中的是否被解释为null? (这里使用和未定义的属性是在父类中定义的):

page.php:

<?php
include("includes/database_classes.php");

new database_connection;
new database_query("SELECT * FROM users");

?>

...和database_classes.php:

<?php
/*----------------------------------------------------------------------------------------------------*/
    class database_connection
    {   
        protected $username = 'root';
        protected $password = '';
        protected $hostname = 'localhost';
        protected $database = 'assistant';  
        protected $database_handle;

        function connect()
        {
            try
            {
                $database_handle = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
            }

            catch (PDOException $e) 
            {
                print "Error!: " . $e ->getMessage() . "<br/>";
                die();
            }
        }
    }

/*----------------------------------------------------------------------------------------------------*/
class database_disconnection extends database_connection
{
    function disconnect()
    {
        $database_handle = null;
    }
}

/*----------------------------------------------------------------------------------------------------*/
    class database_query extends database_connection
    {
        protected $mysql_statement;

        function __construct( $mysql_statement )
        {
            $this->mysql_statement = $mysql_statement;

            echo $mysql_statement;

            foreach($this->database_handle->query("$mysql_statement")->fetch_assoc() as $row) {
                print_r($row);
            }
        }

    }

/*----------------------------------------------------------------------------------------------------*/

1 个答案:

答案 0 :(得分:0)

我认为在尝试循环查询SQL查询结果时遇到问题,这是因为您没有包含方法&#34; fetch_assoc()&#34;

而不是:

foreach($this->database_handle->query("$mysql_statement") as $row);

为什么不呢?

foreach($this->database_handle->query("$mysql_statement")->fetch_assoc() as $row)