mysql php增删改查

admin MySql PHP编程评论707字数 1925阅读模式

连接数据库

$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "myDB";

$conn = mysqli_connect($servername, $username, $password, $dbname);

检查连接是否成功

if (!$conn) {
    die("连接失败: " . mysqli_connect_error());
}

查询数据

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);

输出查询结果

if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 结果";
}

插入数据

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

更新数据

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if (mysqli_query($conn, $sql)) {
    echo "记录更新成功";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

删除数据

$sql = "DELETE FROM MyGuests WHERE id=3";
if (mysqli_query($conn, $sql)) {
    echo "记录删除成功";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

关闭连接

mysqli_close($conn);

安整的PHP代码

<?php
// 连接数据库
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "myDB";

$conn = mysqli_connect($servername, $username, $password, $dbname);

// 检查连接是否成功
if (!$conn) {
    die("连接失败: " . mysqli_connect_error());
}

// 查询数据
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);

// 输出查询结果
if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 结果";
}

// 插入数据
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
    echo "新记录插入成功";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

// 更新数据
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if (mysqli_query($conn, $sql)) {
    echo "记录更新成功";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

// 删除数据
$sql = "DELETE FROM MyGuests WHERE id=3";
if (mysqli_query($conn, $sql)) {
    echo "记录删除成功";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

// 关闭连接
mysqli_close($conn);
?>

版权声明:文章图片资源来源于网络,如有侵权,请留言删除!!!
admin
  • 本文由 发表于 2023年5月17日 17:52:38
  • 转载请务必保留本文链接:https://www.58pxe.com/10621.html
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: