Skip to content

Instantly share code, notes, and snippets.

@inuvalogic
Last active January 21, 2017 06:31
Show Gist options
  • Save inuvalogic/e2472f1c0139791d7161304f446f25bd to your computer and use it in GitHub Desktop.
Save inuvalogic/e2472f1c0139791d7161304f446f25bd to your computer and use it in GitHub Desktop.
<?php
$hostname = 'localhost';
$dbname = 'latihan';
$username = 'root';
$password = '';
try {
$pdo = new PDO('mysql:host='.$hostname.';dbname='.$dbname, $username, $password, array(
PDO::ATTR_PERSISTENT => true
));
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
echo "Ada error gan: ".$e->getMessage();
}
//--------------------------------------------- select
$sql_select = "SELECT * FROM `artikel`";
$query = $pdo->prepare($sql_select);
$query->execute();
$row = $query->fetchAll();
foreach ($row as $data) {
echo "<h3>Judul = ".$data['judul']."</h3>";
echo "<p>Isi = ".$data['isi']."</p>";
}
//--------------------------------------------- insert
$judul = "judul artikel yang baru";
$isi = "isi artikel baru yang akan diinputkan ke database";
$sql_insert = "INSERT INTO `artikel` (`judul`,`isi`) VALUES (?,?)";
$query = $pdo->prepare($sql_insert);
$query->bindParam(1, $judul);
$query->bindParam(2, $isi);
$query->execute();
//---------------------------------------------update
$judul = "ganti dengan judul baru";
$isi = "ganti isi artikel dengan yang baru";
$id = 1;
$sql_update = "UPDATE `artikel` SET `judul` = ?, `isi` = ? WHERE `id` = ?";
$query = $pdo->prepare($sql_update);
$query->bindParam(1, $judul);
$query->bindParam(2, $isi);
$query->bindParam(3, $id);
$query->execute();
//--------------------------------------------- delete
$id = 2;
$sql_delete = "DELETE FROM `artikel` WHERE `id` = ?";
$query = $pdo->prepare($sql_delete);
$query->execute(array($id));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment