1. Buat database kampus.db
MariaDB [(none)]> Create Database kampus;2. Gunakan database kampus.db
Query OK, 1 row affected (0.05 sec)
MariaDB [(none)]> Use kampus;3. Membuat tabel mahasiswa
Database changed
MariaDB [kampus]> Create Table mahasiswa(4. Deskripsi tabel mahasiswa
-> id char(5) not null,
-> nama varchar(50) not null,
-> primary key (id))
-> Engine = InnoDB;
Query OK, 0 rows affected (0.36 sec)
MariaDB [kampus]> Desc mahasiswa;
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
id | char(5) | NO | PRI | NULL | |
nama | varchar(50) | NO | NULL |
5. Buat folder baru contoh di C:\xampp\htdocs\contoh.
6. Didalam contoh buat folder include, masuk kedalam folder include tambahkan 3 file PHP.
7. Masuk di folder include C:\xampp\htdocs\contoh\include. Buat Konfigurasi.php, Koneksi.php dan Fungsi.php
8. Membuat file PHP dengan nama Konfigurasi.php
<?php9. Membuat file PHP dengan nama Koneksi.php
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "PasswordDatabase");
define("DB_DATABASE", "kampus");
?>
<?php10. Membuat file PHP dengan nama Fungsi.php
class Koneksi
{
private $conn;
public function connect()
{
require_once 'include/Konfigurasi.php';
$this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
return $this->conn;
}
}
?>
<?php
class Fungsi {
private $conn;
function __construct() {
require_once 'Koneksi.php';
$db = new Koneksi();
$this->conn = $db->connect();}
function __destruct() {}
public function tampilMahasiswa() {
$stmt = $this->conn->prepare("SELECT * FROM mahasiswa");
$stmt->execute();
$user = $stmt->get_result();
$stmt->close();
return $user;
}
}?>
11. Di dalam folder contoh C:\xampp\htdocs\contoh tambahkan file PHP tampilmahasiswa.php
<?phpKegunaan
require_once 'include/Fungsi.php';
$db = new Fungsi();
$response = array();
if($_SERVER['REQUEST_METHOD']=='GET') {
$result = $db->tampilMahasiswa();
while ($row = $result->fetch_assoc())
{
array_push($response, array("id"=>$row['id'],"nama"=>$row['nama']));
$data[] = $row;
}
echo json_encode($data);
}
else
{
$response["error"] = TRUE;
$response["error_msg"] = "Koneksi jaringan bermasalah.";
echo json_encode($response);
}
?>
tampilmahasiswa.php untuk menampilkan data mahasiswa.
Comments