最新的Web开发教程
 

PHP更新数据在MySQL


更新数据在一个MySQL表使用的MySQLi和PDO

UPDATE语句用来更新表中现有的记录:

UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value 

请注意在UPDATE语法WHERE子句:WHERE子句指定哪些记录或应该更新记录。 如果省略WHERE子句,所有记录都将被更新!

要了解更多有关SQL,请访问我们的SQL教程

让我们来看看"MyGuests"表:

ID 名字 电子邮件 reg_date
1 约翰 母鹿 [email protected] 2014年10十四时26分15秒
2 玛丽 [email protected] 2014年10月23日十时22分30秒

下面的实施例在更新与ID = 2的记录"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 = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating 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 = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if (mysqli_query($conn, $sql)) {
    echo "Record updated successfully";
} else {
    echo "Error updating 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 = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

    // Prepare statement
    $stmt = $conn->prepare($sql);

    // execute the query
    $stmt->execute();

    // echo a message to say the UPDATE succeeded
    echo $stmt->rowCount() . " records UPDATED 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秒