我多次调用此函数时遇到问题
索引.php
<?php
function check_status($id){
require_once ('inc/connect.php');
try {
$query = $db->prepare('SELECT `usage` FROM `room` WHERE `id` = :id');
$query->execute(array(':id' => $id));
$row = $query ->fetch(PDO::FETCH_NUM);
}catch (PDOException $e) {
exit($e->getMessage());
}
if($row[0]>0) {
$msg = 'Room: Closed'; }
else {
$msg = 'Room: Opened'; }
echo $msg;
$db = null;
}
?>
<body>
<?php echo check_status("1"); ?>
<?php echo check_status("2"); ?>
</body>
连接.php
<?php
$dbhost = ('localhost');
$dbname = ('db_name');
$dbuser = ('user_name');
$dbpass = ('test');
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
?>
第一个电话工作正常,但第二个,说这个错误:
Fatal error: Call to a member function prepare() on a non-object in /home/public_html/index.php on line 6
最好的方法是什么?