db_class.php
<?php
class db_mysql
{
private $dbhost;
private $dbusername;
private $dbpassword;
private $db;
//Class is called with all parameters to make a successful connection.
//
function __construct($dbhost,$dbusername,$dbpassword,$db)
{
global $dbh;
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$db", $dbusername, $dbpassword);
foreach($dbh->query('show tables;') as $row) {
print_r($row);
}
//$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
//Function to execute a query in the database and return result in a array
//
function db_mysql_query($queryst)
{
foreach($dbh->query($queryst) as $row) {
print_r($row);
}
}
}
索引.php:
<?php
include 'db_class.php';
$db_m = new db_mysql('localhost','root','','arsaas');
$db_m->db_mysql_query('show tables;');
?>
执行 index.php 会出现以下错误: 注意:未定义变量:第 32 行 C:\xampp\htdocs\srry\db_class.php 中的 dbh
致命错误:在 C:\xampp\htdocs\srry\db_class.php 第 32 行对非对象调用成员函数 query()
为什么在类构造函数中实例化并声明为全局变量时,它说 dbh 是未定义的变量?
任何帮助表示赞赏。提前致谢。
增强现实