# CRUD Sederhana

### CRUD Sederhana

Langkah awal, buatlah direktori baru pada **htdocs** lalu beri nama **aplikasi\_sederhana** setelah itu buatlah berkas/file baru dengan nama **koneksi.php** lalu ketikkan Kode PHP berikut ini :

### koneksi.php

{% code title="koneksi.php" %}

```php
<?php
$server   = 'localhost';
$username = 'root';
$password = '';
$database = 'web2';

$conn = mysqli_connect($server, $username, $password, $database);
if (!$conn) {
    die('Gagal terhubung: ' . mysqli_connect_error());
}
?>
```

{% endcode %}

Setelah itu buka browser dan ketikkan <http://localhost/phpmyadmin/> buat database baru dan beri nama **web2** lalu ke tab SQL dan ketikkan Query Berikut:

{% code title="Tabel Mahasiswa" %}

```sql
CREATE TABLE `mahasiswa`(
    `id` INT(8) NOT NULL AUTO_INCREMENT,
    `npm` CHAR(20) NOT NULL,
    `nama` VARCHAR(40) NOT NULL,
    PRIMARY KEY(`id`),
    UNIQUE KEY `npm`(`npm`)
) ENGINE = INNODB;

INSERT INTO `mahasiswa` (`id`, `npm`, `nama`) VALUES
(1, '201401', 'Jokowi'),
(2, '201402', 'Prabowo');
```

{% endcode %}

Setelah itu anda buat file **index.php** lalu ketikkan kode PHP seperti berikut:

### index.php

{% code title="index.php" %}

```php
<?php require 'koneksi.php'; ?>
<!DOCTYPE html>
<html>
<head>
	<title>DATA MAHASISWA</title>
</head>
<body>
	<p><a href="form_tambah.php">TAMBAH</a></p>
	<table border="1" cellpadding="2" cellspacing="2" width="60%">
		<thead>
			<tr>
				<th>No</th>
				<th>NPM</th>
				<th>Nama</th>
				<th>Aksi</th>
			</tr>
		</thead>
		<tbody>
			<?php 
				$sql = 'SELECT * FROM mahasiswa';
				$data = mysqli_query($conn, $sql);
				$no=(int)1;
				foreach ($data as $rows): ?>
				<tr>
					<td><?php echo $no++ ?></td>
					<td><?php echo $rows['npm'] ?></td>
					<td><?php echo $rows['nama'] ?></td>
					<td>
						<a href="form_ubah.php?id=<?php echo $rows['id']?>">Ubah</a>
						<a href="hapus.php?id=<?php echo $rows['id']?>">Hapus</a>
					</td>
				</tr>
			<?php endforeach?>
		</tbody>
	</table>
</body>
</html>
```

{% endcode %}

Lalu jika anda klik tautan atau link ubah akan dilempar ke file **form\_ubah.php** dan memberikan parameter id untuk mendapatkan value berdasarkan kolom id dari tabel Mahasiswa. lalu buatlah file form\_ubah.php dan ketikkan kode PHP seperti berikut:

### form\_ubah.php

{% code title="form\_ubah.php" %}

```php
<?php 
require 'koneksi.php'; 
$id_mhs = $_REQUEST['id'];
$sql = "SELECT * FROM mahasiswa WHERE id='$id_mhs'";
$result = mysqli_query($conn,$sql);
foreach ($result as $rows) {
	$id   = $rows['id'];
	$npm  = $rows['npm'];
	$nama = $rows['nama'];
}
?>
<!DOCTYPE html>
<html>
<head>
	<title>UBAH DATA MAHASISWA</title>
</head>
<body>
	<form action="ubah.php" method="POST">
		<input type="hidden" name="txtid" value="<?php echo $id ?>">
		<label for="">NPM:</label>
		<input type="text" name="txtnpm" value="<?php echo $npm ?>">
		<label for="">NAMA:</label>
		<input type="text" name="txtnama" value="<?php echo $nama ?>">
		<button type="submit">UBAH</button>
	</form>
</body>
</html>
```

{% endcode %}

Ketika anda menekan tombol UBAH maka action dilempar ke ubah.php dan akan melakukan UPDATE data dengan Query, anda buat file ubah.php dan ketikkan kode PHP seperti berikut:

### ubah.php

{% code title="ubah.php" %}

```php
<?php require 'koneksi.php';
$data = array(
	'npm'  => $_POST['txtnpm'],
	'nama' => $_POST['txtnama'],
);
$where = $_POST['txtid'];
$cols = array();

foreach($data as $key=>$val) {
	$cols[] = "$key = '$val'";
}

$sql = "UPDATE mahasiswa SET ". implode(',', $cols). "WHERE id=".$where;
mysqli_query($conn,$sql);
if ($sql) {
   echo 'Data berhasil diubah <br/><a href="index.php">Kembali</a>';
} else {
   echo 'Error cuyy: ' . $sql . '<br>' . mysqli_error($conn);
}

mysqli_close($conn);
?>
```

{% endcode %}

Selanjutnya anda membuat form\_tambah.php guna menambahkan data secara otomatis melalui form tersebut, anda bisa ketikkan kode PHP seperti berikut:

### form\_tambah.php

{% code title="form\_tambah.php" %}

```php
<!DOCTYPE html>
<html>
<head>
	<title>TAMBAH DATA MAHASISWA</title>
</head>
<body>
	<form action="simpan.php" method="POST">
		<label for="">NPM:</label>
		<input type="text" name="txtnpm" placeholder="NPM" required="true">
		<label for="">NAMA:</label>
		<input type="text" name="txtnama" placeholder="NAMA" required="true">
		<button type="submit">SIMPAN</button>
	</form>
</body>
</html>
```

{% endcode %}

Jika tombol SIMPAN ditekan maka akan muncul fill validation atau validasi field yang harus diisi. Itulah kelebihan dari HTML5 dengan atibut required="true" dan jika field anda sudah isikan semua maka akan dikirim ke file simpan.php anda bisa ketikkan kode PHP seperti berikut:

### simpan.php

{% code title="simpan.php" %}

```php
<?php 
require 'koneksi.php';
$data = array(
	'npm'  => $_POST['txtnpm'],
	'nama' => $_POST['txtnama'],
);

$key = array_keys($data);

$val = array_values($data);

$sql = "INSERT INTO mahasiswa(".implode(', ', $key) . ") ". "VALUES ('".implode("', '", $val) . "')";

mysqli_query($conn,$sql);

if ($sql) {echo 'Data berhasil disimpan <br/><a href="index.php">Kembali</a>';}
else {echo 'Error cuyy: ' . $sql . '<br>' . mysqli_error($conn);}
mysqli_close($conn);
?>
```

{% endcode %}

### hapus.php

{% code title="hapus.php" %}

```php
<?php
require 'koneksi.php';
$id = $_REQUEST['id'];
$sql = mysqli_query($conn, "DELETE FROM mahasiswa WHERE id='$id'");
header("Location:index.php");
?>
```

{% endcode %}

{% embed url="<https://github.com/herusulistiono/Web-Lanjut-Pandemi>" %}
Download/Unduh File
{% endembed %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://herusulistiono.gitbook.io/programming/web-programming/server-side-scripting/crud-sederhana.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
