mysql php增刪改查

admin MySql PHP編程評(píng)論1,076字?jǐn)?shù) 1925閱讀模式

連接數(shù)據(jù)庫(kù)

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

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

檢查連接是否成功

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

查詢數(shù)據(jù)

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

輸出查詢結(jié)果

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 結(jié)果";
}

插入數(shù)據(jù)

$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);
}

更新數(shù)據(jù)

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

刪除數(shù)據(jù)

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

關(guān)閉連接

mysqli_close($conn);

安整的PHP代碼

<?php
// 連接數(shù)據(jù)庫(kù)
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "myDB";

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

// 檢查連接是否成功
if (!$conn) {
    die("連接失敗: " . mysqli_connect_error());
}

// 查詢數(shù)據(jù)
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);

// 輸出查詢結(jié)果
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 結(jié)果";
}

// 插入數(shù)據(jù)
$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);
}

// 更新數(shù)據(jù)
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if (mysqli_query($conn, $sql)) {
    echo "記錄更新成功";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

// 刪除數(shù)據(jù)
$sql = "DELETE FROM MyGuests WHERE id=3";
if (mysqli_query($conn, $sql)) {
    echo "記錄刪除成功";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

// 關(guān)閉連接
mysqli_close($conn);
?>

版權(quán)聲明:文章圖片資源來(lái)源于網(wǎng)絡(luò),如有侵權(quán),請(qǐng)留言刪除!!!
廣告也精彩
admin
  • 本文由 發(fā)表于 2023年5月17日 17:52:38
  • 轉(zhuǎn)載請(qǐng)務(wù)必保留本文鏈接:http://yudch.cn/10621.html
匿名

發(fā)表評(píng)論

匿名網(wǎng)友 填寫(xiě)信息

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