我需要一个mysql数据库连接类
时间: 2023-05-30 09:07:45 浏览: 146
以下是一个简单的MySQL数据库连接类的示例代码:
```php
class MySQLDatabase {
private $host = "localhost";
private $username = "username";
private $password = "password";
private $database = "database";
private $connection;
public function __construct() {
$this->connection = mysqli_connect($this->host, $this->username, $this->password, $this->database);
if (!$this->connection) {
die("Connection failed: " . mysqli_connect_error());
}
}
public function query($sql) {
$result = mysqli_query($this->connection, $sql);
if (!$result) {
die("Query failed: " . mysqli_error($this->connection));
}
return $result;
}
public function escapeString($string) {
return mysqli_real_escape_string($this->connection, $string);
}
public function numRows($result) {
return mysqli_num_rows($result);
}
public function insertId() {
return mysqli_insert_id($this->connection);
}
public function __destruct() {
mysqli_close($this->connection);
}
}
```
使用方法:
```php
$db = new MySQLDatabase();
$sql = "SELECT * FROM users";
$result = $db->query($sql);
while ($row = mysqli_fetch_assoc($result)) {
echo $row['username'] . "<br>";
}
```
阅读全文