WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP Update Data in MySQL


Update Data In a MySQL Table Using MySQLi and PDO

The UPDATE explanation is utilized to refresh existing records in a table:

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

To study SQL, it would be ideal if you visit our SQL tutorial.

Let's take a gander at the "MyGuests" table:

id firstname lastname email reg_date
1 John Doe john@example.com 2014-10-22 14:26:15
2 Mary Moe mary@example.com 2014-10-23 10:22:30

The following precedents refresh the record with id=2 in the "MyGuests" table:

Example (MySQLi Object-oriented)

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

//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
/Check connection
in the event that ($conn->connect_error) {
    die("Connection fizzled: " . $conn->connect_error);
}

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

if ($conn->query($sql) === TRUE) {
    reverberation "Record refreshed successfully";
} else {
    reverberation "Error refreshing record: " . $conn->error;
}

$conn->close();
?>

Example (MySQLi Procedural)

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

//Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
/Check connection
on the off chance that (!$conn) {
    die("Connection fizzled: " . mysqli_connect_error());
}

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

if (mysqli_query($conn, $sql)) {
    reverberation "Record refreshed successfully";
} else {
    reverberation "Error refreshing record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Example (PDO)

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

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    /set the PDO mistake 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();

   /reverberation a message to state the Refresh succeeded
    reverberation $stmt->rowCount() . " records Refreshed successfully";
    }
catch(PDOException $e)
    {
    reverberation $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?>

After the record is refreshed, the table will look like this:

id firstname lastname email reg_date
1 John Doe john@example.com 2014-10-22 14:26:15
2 Mary Doe mary@example.com 2014-10-23 10:22:30