dongxiang3648 2015-06-06 15:29
浏览 15
已采纳

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

I'm beginning php/MySql and have been asked to use a class to access my database. I can get the display to work when I have all my code in one file but when I try to call the class from another file, I get nothing.

This is the one that works:

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

?>

This is my code to call the class:

<?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); 
?>

This is my class:

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

}

?>

Any help appreciated

  • 写回答

2条回答 默认 最新

  • drnxnbf199049 2015-06-06 16:40
    关注

    Change this line as below (remove the dollar sign from query and myConnection):

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

    Plus you might need to call your list_users function using the code below (right after instantiating your class! Pass your defined variables to constructor instead of their actual values):

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

    Also constructors are written with two underscores like this:

    public function __construct
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动