云主机测评网云主机测评网云主机测评网

云主机测评网
www.yunzhuji.net

php7操作mysql数据库_Mysql数据库

在PHP7中,我们通常使用mysqli或PDO扩展来操作MySQL数据库,以下是一些基本操作的示例:

(图片来源网络,侵删)

1、连接数据库

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接
if ($conn>connect_error) {
    die("连接失败: " . $conn>connect_error);
} 
echo "连接成功";
?>

2、查询数据

<?php
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn>query($sql);
if ($result>num_rows > 0) {
    // 输出数据
    while($row = $result>fetch_assoc()) {
        echo "id: " . $row["id"]. " Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 结果";
}
$conn>close();
?>

3、插入数据

<?php
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn>query($sql) === TRUE) {
    echo "新记录插入成功";
} else {
    echo "Error: " . $sql . "<br>" . $conn>error;
}
$conn>close();
?>

4、更新数据

<?php
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn>query($sql) === TRUE) {
    echo "记录更新成功";
} else {
    echo "更新错误: " . $conn>error;
}
$conn>close();
?>

5、删除数据

<?php
$sql = "DELETE FROM MyGuests WHERE id=1";
if ($conn>query($sql) === TRUE) {
    echo "记录删除成功";
} else {
    echo "删除错误: " . $conn>error;
}
$conn>close();
?>
打赏
版权声明:主机测评不销售、不代购、不提供任何支持,仅分享信息/测评(有时效性),自行辨别,请遵纪守法文明上网。
文章名称:《php7操作mysql数据库_Mysql数据库》
文章链接:https://www.yunzhuji.net/xunizhuji/197508.html

评论

  • 验证码