PHP制作怎么连接数据库
时间: 2024-11-03 07:12:52 浏览: 11
在PHP中,连接数据库通常通过使用MySQLi (MySQL Improved) 或 PDO (PHP Data Objects) 函数库来完成。以下是基本步骤:
1. **MySQLi**连接示例:
```php
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接是否成功
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
?>
```
2. **PDO**连接示例:
```php
<?php
$host = 'localhost';
$db = 'your_database';
$user = 'your_username';
$pass = 'your_password';
try {
$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
// 设置PDO错误模式为异常
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected to database.";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
```
阅读全文