我正在尝试学习OOP PHP的基础知识但是我被困在这个部分:
<?php
class Database {
private $dbuser;
private $dbpass;
private $dbhost;
private $database;
private $link;
private $connection;
function __construct($dbhost, $dbuser, $dbpass, $database) {
$this->dbhost = $dbhost;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
$this->database = $database;
$this->link = mysql_connect($this->dbhost, $this->dbuser, $this->dbpass);
$this->link = mysql_select_db($this->database);
return true;
}
function NewQuery($query) {
$execute = mysql_query($query);
if (!$execute) die('Invalid query: ' . mysql_error());
return $execute;
}
function __destruct() {
mysql_close($this->link);
}
}
在我的索引页面上,我在mysql_close上收到此错误。我有什么办法可以在__destruct()类上修复它吗?
Warning: mysql_close() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\projects\oop\classes\database.php on line 33
答案 0 :(得分:2)
如果您查看documentation for mysql_select_db()
,您看到的第一件事就是红色大框,表示您不应再使用mysql_
函数。
除此之外,页面还说该函数在成功时返回true
,在出错时返回false
。这意味着你用布尔值覆盖了保存连接的变量($this->link
),当你试图关闭它时会导致错误。
简单的解决方案是不将数据库选择的返回值存储在任何地方,或者为其使用单独的变量。
答案 1 :(得分:0)
让我们继续PDO
!
<?php
class Database {
private $con;
public function __construct($dbname, $dbhost, $dbuser, $dbpass) {
$this->con = new PDO(
sprintf('mysql:dbname=%s;host=%s;charset=utf8',
$dbname,
$dbhost
),
$dbuser,
$dbpass,
array(
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
)
);
}
function execute($sql, $params = array()) {
$stmt = $this->con->prepare($sql);
foreach ($params as $key => $v) {
list($value, $type) = is_array($v) ?
$v :
array($v, PDO::PARAM_STR)
;
$stmt->bindValue($key, $value, $type);
}
$stmt->execute();
return $stmt;
}
}
使用示例:
$_POST['age'] = '15'; // user input
try {
if (!isset($_POST['age']) || !is_string($age = $_POST['age'])) {
throw new Exception('parameter $_POST["age"] required');
}
$db = new Database('testdb', 'localhost', 'root', '');
$params = array(
':age' => array(
$age,
PDO::PARAM_INT,
)
);
$sql = 'SELECT COUNT(*) FROM people WHERE age = :age';
printf("The number of %d years old people is %d\n",
$age,
$db->execute($sql, $params)->fetchColumn()
);
$sql = 'SELECT * FROM people WHERE age = :age';
foreach ($db->execute($sql, $params) as $user) {
echo "\n";
printf("Name : %s\n", $user->name);
printf("Age : %d\n", $user->age);
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}