最新的Web開發教程
 

PHP刪除數據從MySQL


刪除數據從一個MySQL表使用的MySQLi和PDO

DELETE語句用來從表中刪除記錄:

DELETE FROM table_name
WHERE some_column = some_value

注意:在刪除語法WHERE子句:WHERE子句指定哪些記錄或應該被刪除的記錄。 如果省略WHERE子句,所有記錄都將被刪除!

要了解更多有關SQL,請訪問我們的SQL教程

讓我們來看看"MyGuests"表:

ID 名字 電子郵件 reg_date
1 約翰 母鹿 [email protected] 2014年10十四時26分15秒
2 瑪麗 [email protected] 2014年10月23日十時22分30秒
3 朱麗葉 杜利 [email protected] 2014年10月26日10時48分23秒

下面的實施例刪除與ID = 3的記錄在"MyGuests"表:

實施例(MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";

if ($conn->query($sql) === TRUE) {
    echo "Record deleted successfully";
} else {
    echo "Error deleting record: " . $conn->error;
}

$conn->close();
?>

實施例(MySQLi Procedural)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";

if (mysqli_query($conn, $sql)) {
    echo "Record deleted successfully";
} else {
    echo "Error deleting record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

實施例(PDO)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // sql to delete a record
    $sql = "DELETE FROM MyGuests WHERE id=3";

    // use exec() because no results are returned
    $conn->exec($sql);
    echo "Record deleted successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?>

記錄被刪除後,該表將是這樣的:

ID 名字 電子郵件 reg_date
1 約翰 母鹿 [email protected] 2014年10十四時26分15秒
2 瑪麗 [email protected] 2014年10月23日十時22分30秒