php错误在非对象上调用成员函数query() [英] php error Call to a member function query() on a non-object
问题描述
db_class.php
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);
}
}
}
index.php:
index.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
Executing index.php gives the following error: Notice: Undefined variable: dbh in C:\xampp\htdocs\srry\db_class.php on line 32
致命错误:在第32行的C:\ xampp \ htdocs \ srry \ db_class.php中的非对象上调用成员函数query()
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\srry\db_class.php on line 32
为什么在实例化dbh并将其声明为类构造函数中的全局变量时说dbh是未定义的变量?
Why does it say dbh is undefined variable when it is instantiated and declared as a global variable in the class constructor?
感谢您的帮助.预先感谢.
Any help is appreciated. Thanks in advance.
AR
推荐答案
db_mysql_query方法未定义变量$ dbh,因此尝试在非对象上调用方法查询无效.您可以将PDO对象($ dbh)存储到构造函数中的db_mysql对象中,并在调用db_mysql_query时使用它.如果仅尝试使用一个数据库连接,则建议您考虑在db_mysql类中使用单例模式. http://www.talkphp.com /advanced-php-programming/1304-how-use-singleton-design-pattern.html
db_mysql_query method doesn't define variable $dbh, therefore trying to call method query on non-object is not working. You could store PDO object ($dbh) into db_mysql object in the constructor and use it when calling db_mysql_query. If you are trying to use only one database connection then I suggest you to consider using singleton pattern in your db_mysql class. http://www.talkphp.com/advanced-php-programming/1304-how-use-singleton-design-pattern.html
这篇关于php错误在非对象上调用成员函数query()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!