class Db{
private $host = "localhost";
private $user ="root";
private $pwd ="";
private $dbName="s_table";
protected function connect(){
$dsn = 'mysql:host='.$this->host .';dbname='.$this->dbName;
$pdo =new PDO($dsn,$this->user,$this->pwd);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
}
}
include 'DB.php';
class User extends Db{
public function all_user(){
$sql="SELECT * FROM s_table";
$stmt=$this->connect()->query($sql);
while ($row = $stmt->fetch()) {
echo $row['name'];
}
}
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
include 'User.php';
$all=new User();
$all->all_user();
</body>
</html>
I think it might help if we had the ability to see User.php
. I’m a little rusty on my PHP but I don’t believe this code snippet provides enough for us to work on.
Is this line suppose to have a ;
or is it suppose to have a `$’. I am not very good very PHP, but have experience in other programming languages.
I am talking about the variable dbname?
$dsn = 'mysql:host='.$this->host .';dbname='.$this->dbName;
When you’re using the $this->dbName;
You’re referencing the current objects dbName
.
In this case, I believe the syntax is correct. Since you are in the Db
class, $this
has the parent object of Db
if I’m not mistaken.
You can read more about the $this
syntax at this wonderful post.
1 Like