在PHP中执行SQL查询是Web开发中的常见任务,主要通过PDO(PHP Data Objects)或MySQLi扩展来实现。以下是使用这两种方法执行SQL查询的基础概念、优势、类型和应用场景。
PDO:
MySQLi:
PDO:
MySQLi:
查询类型:
<?php
try {
$dsn = 'mysql:host=localhost;dbname=testdb;charset=utf8';
$username = 'your_username';
$password = 'your_password';
$pdo = new PDO($dsn, $username, $password);
// SELECT 查询
$stmt = $pdo->query('SELECT * FROM users');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['username'] . '<br>';
}
// INSERT 查询
$stmt = $pdo->prepare('INSERT INTO users (username, email) VALUES (:username, :email)');
$stmt->bindParam(':username', 'newuser');
$stmt->bindParam(':email', 'newuser@example.com');
$stmt->execute();
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "testdb";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SELECT 查询
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["username"] . "<br>";
}
} else {
echo "0 results";
}
// INSERT 查询
$sql = "INSERT INTO users (username, email) VALUES ('newuser', 'newuser@example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
SQL注入:
prepare
和bindParam
方法)。连接失败:
性能问题:
通过以上方法和示例代码,您可以在PHP中有效地执行SQL查询,并解决常见的技术问题。
领取专属 10元无门槛券
手把手带您无忧上云