PHP Update Data in MySQL

The php update data is used to update existing data in the database.

[php]<?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();
?>[/php]

Code Explanation:

We are using $sql statement to update the database. In the statement we have instructed php script to update MyGuests database and set the lastname field Doe WHERE id is 2.

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

If everything goes well, your database will be updated.

Related Posts

Leave a Reply