part 1 update delete

Koneksi.php

 <?php 

$con = mysqli_connect("localhost", "root", "", "siswa");

if (!$con) {

  echo "Koneksi Gagal";

}

function hapus ($data) {

  global $con;

  $id = $_GET['id'];

  $sql = mysqli_query($con, "DELETE FROM data WHERE id = '$id'");

  return mysqli_affected_rows($con);


}




function edit($data) {


  global $con;




  $id = $_GET['id'];


  $nama = $_POST['nama'];




  $sql = "UPDATE data SET


      nama = '$nama'


      WHERE id = '$id'";


  $query = mysqli_query($con, $sql);




  return mysqli_affected_rows($con);


}




 ?>

Index.php

<?php

require 'koneksi.php';

 ?> 


<!DOCTYPE html>

<html>

<head>

  <title>Tugas</title>

</head>

<body>

   <table>

    <tr>

          <th>No</th>

          <th>Nama</th>

          <th>Aksi</th>

    </tr>

        <?php 

        $no = 1;

        $sql = mysqli_query($con, "SELECT * FROM data");

        foreach ($sql as $data) {

         ?>


          <tr>

            <td><?php echo $no++; ?></td>

            <td><?php echo $data["nama"]; ?></td>

            <td>

              <a href="hapus.php?id=<?= $data["id"]; ?>"> hapus </a>

              <a href="edit.php?id=<?= $data["id"]; ?>"> edit  </a>

            </td>

          </tr>

        <?php } ?>

      </table>

</body>


</html>


hapus.php

<?php 

require 'koneksi.php';

$id = $_GET['id'];

if( hapus($id) > 0 ) {

  echo "

    <script>

      alert('data berhasil dihapus');

      document.location.href = 'index.php';

    </script>

  ";


} else {

  echo "

    <script>

      alert('data gagal dihapus')

    </script>


  ";


}




 ?>


edit.php

<?php 




require 'koneksi.php';




$id = $_GET['id'];




if (isset($_POST['submit'])) {


if (edit($_POST) > 0) {


echo "


<script>


alert('Data Berhasil Diubah');


document.location.href = 'index.php';


</script>


";


} else {


echo "


<script>


alert('Buku Gagal Diubah');


</script>


";

}

}

 ?>


<!DOCTYPE html>


<html>


<head>

<title>Edit</title>

<form method="POST">

<?php 

$sql = mysqli_query($con, "SELECT * FROM data WHERE id = '$id'");

foreach ($sql as $row) {

?>


  <h5 class="card-title text-center">Edit Data</h5>


  <input type="number" name="id" value="<?php echo $id; ?>" hidden>


  <input type="text" class="form-control" name="nama" id="nama" value="<?php echo $row["nama"]; ?>">


  <label for="nama">Nama</label>


  <?php } ?>


  <input type="submit" name="submit" value="Edit Data" class="btn btn-warning mb-3 fw-bold">


</div>


</form>


</div>


</div>

</div>

</body>

</html>

Komentar

Postingan Populer