在PHP7中,可以使用mysqli扩展来连接数据库以及进行增删查改操作。下面是详细的步骤:
连接数据库:
$servername = "localhost";
$username = "root";
$password = "password";
$database = "mydb";
// 创建连接
$conn = new mysqli($servername, $username, $password, $database);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
插入数据:
$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;
}
查询数据:
$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 结果";
}
更新数据:
$sql = "UPDATE users SET email='john.doe@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;
}
关闭连接:
$conn->close();
以上是使用mysqli方法连接数据库以及进行增删查改操作的详细步骤。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站