如何使用PHP进行数据库连接和操作?
使用PHP进行数据库连接和操作是Web开发中非常常见且重要的任务。PHP提供了多种扩展和函数来与各种数据库进行交互,其中最常见的是MySQLi(MySQL Improved)和PDO(PHP Data Objects)。这两种方法都提供了灵活且强大的方式来连接和操作数据库。
php复制代码
| |
$servername = "localhost"; // 数据库服务器地址 | |
$username = "username"; // 数据库用户名 | |
$password = "password"; // 数据库密码 | |
$dbname = "database_name"; // 数据库名 | |
// 创建连接 | |
$conn = new mysqli($servername, $username, $password, $dbname); | |
// 检查连接是否成功 | |
if ($conn->connect_error) { | |
die("连接失败: " . $conn->connect_error); | |
} | |
?> |
php复制代码
| |
// 假设已经建立了数据库连接 $conn | |
// 查询语句 | |
$sql = "SELECT * FROM users"; | |
// 执行查询 | |
$result = $conn->query($sql); | |
// 检查查询结果 | |
if ($result->num_rows > 0) { | |
// 输出数据 | |
while($row = $result->fetch_assoc()) { | |
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " | |
} | |
} else { | |
echo "0 结果"; | |
} | |
// 关闭结果集 | |
$result->close(); | |
?> |
php复制代码
| |
// 插入数据 | |
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')"; | |
if ($conn->query($sql) === TRUE) { | |
echo "新记录插入成功"; | |
} else { | |
echo "Error: " . $sql . " | |
} | |
// 更新数据 | |
$sql = "UPDATE users SET email='newemail@example.com' WHERE id=1"; | |
if ($conn->query($sql) === TRUE) { | |
echo "记录更新成功"; | |
} else { | |
echo "Error updating record: " . $conn->error; | |
} | |
// 删除数据 | |
$sql = "DELETE FROM users WHERE id=1"; | |
if ($conn->query($sql) === TRUE) { | |
echo "记录删除成功"; | |
} else { | |
echo "Error deleting record: " . $conn->error; | |
} | |
?> |
php复制代码
| |
// 预处理语句 | |
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)"); | |
$stmt->bind_param("ss", $name, $email); | |
$name = "John Doe"; | |
$email = "john@example.com"; | |
// 执行预处理语句 | |
if ($stmt->execute()) { | |
echo "新记录插入成功"; | |
} else { | |
echo "Error: " . $stmt->error; | |
} | |
$stmt->close(); | |
?> |
PDO提供了一种数据访问抽象层,这意味着你可以使用相同的代码来连接和操作多种数据库。
php复制代码
| |
try { | |
$dsn = "mysql:host=localhost;dbname=database_name;charset=utf8"; | |
$options = [ | |
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, | |
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, | |
PDO::ATTR_EMULATE_PREPARES => false, | |
]; | |
$pdo = new PDO($dsn, 'username', 'password', $options); | |
} catch (\PDOException $e) { | |
throw new \PDOException($e->getMessage(), (int)$e->getCode()); | |
} | |
?> |
php复制代码
| |
try { | |
$sql = "SELECT * FROM users"; | |
$stmt = $pdo->query($sql); | |
while ($row = $stmt->fetch()) { | |
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " | |
} | |
} catch (\PDOException $e) { | |
echo "查询失败: " . $e->getMessage(); | |
} | |
?> |