尝试使用php中的类从mySQL显示

时间:2015-06-06 15:29:50

标签: php mysql

我开始使用php / MySql并且被要求使用类来访问我的数据库。当我将所有代码放在一个文件中时,我可以让显示器工作但是当我尝试从另一个文件调用该类时,我什么也得不到。

这是有效的:

<?php

$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'testdb';

$myNewConnection = mysqli_connect($host,$username,$password,$dbname);
$query = "SELECT user_name FROM users" or die ("Error..." . mysqli_error($myNewConnection));

// execute the query
$result = $myNewConnection->query($query);

// display output
while($row = mysqli_fetch_array($result)) {
    echo $row["user_name"] . "<br>";
}

?>

这是我调用该类的代码:

<?php
include("users.php");

$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'testdb';

//initiate the class
$myDB = new MyDB('localhost', 'root', '', 'testdb'); 
//$myDB = new MyDB($host,$username,$password,$dbname); 
?>

这是我的班级:

<?php

class MyDB {

    public $query;
    public $myConnection;

    public function _construct($host,$username,$password,$dbname){

        // establish the connection
        $this->myConnection = mysqli_connect($host,$username,$password,$dbname);
    }
    public function list_users() {

        // create query to list all users
        $this->query = "SELECT user_name FROM users" or die ("Error..." . mysqli_error($this->$myNewConnection));

        // execute the query
        $result = $this->$myConnection->query($this->$query);

        // display output
        while($row = mysqli_fetch_array($result)) {
            echo $row["user_name"] . "<br>";
        }
    }

}

?>

任何帮助表示赞赏

2 个答案:

答案 0 :(得分:3)

如下所示更改此行(从querymyConnection删除美元符号):

$result = $this->myConnection->query($this->query);

Plus 你可能需要使用下面的代码调用你的list_users函数(在实例化你的类之后!将你定义的变量传递给构造函数而不是它们的实际值):

$myDB = new MyDB($host,$username,$password,$dbname);
$myDB->list_users();

构造函数也用两个下划线写成:

public function __construct

答案 1 :(得分:2)

function __construct有两个“_”。在“$”之后删除所有“->”:

<?php

class MyDB {
    public $query;
    public $myConnection;
    public function __construct($host,$username,$password,$dbname){     
        $this->myConnection = mysqli_connect($host,$username,$password,$dbname);
    }
    public function list_users() {
        $this->query = "SELECT user_name FROM users";
        if($result = $this->myConnection->query($this->query)) {
            while($row = mysqli_fetch_array($result)) {
                echo $row["user_name"] . "<br>";
            }
        }
    }
}

你必须运行list_users()

<?php
include("users.php");

$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'testdb';

$myDB = new MyDB($host, $username, $password, $dbname); 
$myDB->list_users();

?>