简体   繁体   中英

php issue with including file

I have 2 files. The first one contains (db.php)

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '123456';
$db = new PDO("mysql:host=$dbhost;dbname=myclass",$dbuser,$dbpass);

The second one contains (users.php)

<?php
include 'db.php';

class Users {

public function register() {

    $query = $db->prepare('INSERT INTO Users(user, pass) VALUES (?,?)');
    $query->bindValue(1,'user');
    $query->bindValue(2,'pass');
    $query->execute();

}
}

$myUser = new Users();

$myUser->register();

?>

When I try to load the second file , the data does not show. And when I try to write "$db->" then nothing appears that I can add in there from the drop down. Do you have an idea why this happens and how can I fix it?

The problem is those variables in the db.php is not accessible inside your class !

Better initialize all those values in the db.php inside your class through a constructor

You gotta do something like this..

class Users {

    private $dbhost,$dbuser,$dbpass,$db;

    public function __construct(){

        $this->dbhost = 'localhost';
        $this->dbuser = 'root';
        $this->dbpass = '123456';
        $this->db = new PDO("mysql:host=$this->dbhost;dbname=myclass",$this->dbuser,$this->dbpass);

    }

    public function register() {

        $query = $this->db->prepare('INSERT INTO Users(user, pass) VALUES (?,?)');
        $query->bindValue(1,'user');
        $query->bindValue(2,'pass');
        $query->execute();

    }
}

$myUser = new Users();
$myUser->register();

You need to inject $db into your class. You can use the constructor:

class Users {

    public function __construct($db) {
        $this->db = $db;
    }

    public function register() {
        $query = $this->db->prepare('INSERT INTO Users(user, pass) VALUES (?,?)');
        // etc...
    }
}

include('db.php');
include('users.php');

$myUser = new Users($db);

Try putting <?php and ?> in db.php. Possibly the code is not being interpreted as PHP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM