在PHP中,可以使用MySQLi扩展或PDO扩展来操作MySQL数据库。下面是一些常见的MySQL操作示例:
使用MySQLi扩展:
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "database";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
使用PDO扩展:
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "连接成功";
} catch(PDOException $e) {
echo "连接失败: " . $e->getMessage();
}
使用MySQLi扩展:
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 结果";
}
使用PDO扩展:
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->rowCount() > 0) {
foreach($result as $row) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 结果";
}
使用MySQLi扩展:
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
使用PDO扩展:
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";
if ($conn->exec($sql)) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->errorInfo();
}
这些示例只是PHP操作MySQL的基本用法,还有很多其他的操作和技巧可以学习。建议阅读相关的文档和教程,以便更全面地了解和学习PHP操作MySQL的知识。
上一篇:php搭建mysql连接池
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站