Home » PHP » Update Data dari Database di PHP MySQL

Update Data dari Database di PHP MySQL

by Hanifah Nurbaeti
by Hanifah Nurbaeti

Update Data Pada Tabel MySQL Menggunakan MySQLi dan PDO

Pernyataan UPDATE digunakan untuk memperbarui catatan yang ada dalam tabel:

UPDATE nama_tabel
SET kolom1 = nilai, kolom2 = nilai2, …
WHERE some_column = some_value

Perhatikan klausa WHERE dalam sintaks UPDATE: Klausa WHERE menentukan record atau record mana yang harus diperbarui. Jika dilangkan klausa WHERE, semua record akan diperbarui!

Mari kita lihat tabel “MyGuests”:

idfirstnamelastnameemailreg_date
1JohnDoe[email protected]2014-10-22 14:26:15
2MaryMoe[email protected]2014-10-23 10:22:30

Contoh berikut memperbarui record dengan id = 2 di tabel “MyGuests”:

Contoh (MySQLi Object-oriented) :

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

// Buat Koneksi
$conn = new mysqli($servername, $username, $password, $dbname);
// Periksa Koneksi
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();
?>

Contoh (MySQLi Prosedural) :

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

// Buat Koneksi
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Periksa Koneksi
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);
?>

Contoh (PDO) :

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

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  // mengatur mode kesalahan PDO ke pengecualian
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

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

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

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

  // echo pesannya untuk mencetak UPDATE Sukses
  echo $stmt->rowCount() . " records UPDATED successfully";
} catch(PDOException $e) {
  echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

Setelah record diperbarui, tabel akan terlihat seperti ini:

idfirstnamelastnameemailreg_date
1JohnDoe[email protected]2014-10-22 14:26:15
2MaryDoe[email protected]2014-10-23 10:22:30

You may also like