Friday, December 12, 2014

Membuat Upload, Edit, dan Hapus Foto/Gambar di PHP


Buat database dengan nama: db_images
Buat tabel dengan nama: tb_images
Buat 2 field yaitu: id (int (3), primary key, auto increment) serta image (varchar(50))
Akan dibutuhkan tiga file php yaitu untuk upload, edit, serta view.
Buat folder untuk menampung foto/gambar di dalam folder project. Contoh beri nama folder tersebut: img
Berikut ini adalah script input_image.php:
<?php
    mysql_connect("localhost","root","");   
    mysql_select_db("db_images");
    $lokasi_file    = $_FILES['gambar']['tmp_name'];
    $nama_file      = $_FILES['gambar']['name'];
    $acak           = rand(1,99);
    $nama_file_unik = $acak.$nama_file;
    $vdir_upload = "img/";
    $vfile_upload = $vdir_upload . $nama_file_unik;
    move_uploaded_file($_FILES["gambar"]["tmp_name"], $vfile_upload);
   
    $simpan=$_POST['simpan'];   
   
    if ($simpan){
        if (empty($lokasi_file)){
        //echo "<center><font color='#FF0000' size='+2'>Maaf Anda belum memilih Gambar<br></font></center>";
        ?><script language="javascript">alert('Maaf Anda belum memilih Gambar')</script><?php
        ?><script>document.location.href="input_image.php";</script><?php
}else{
    mysql_query("INSERT INTO tb_images VALUES ('','$nama_file_unik')")or die (Error.mysql_error());
    //echo "<center><font color='#FF0000' size='+1'>Berhasil disimpan</font></center><br>";
            ?><script language="javascript">alert('Images Berhasil Disimpan')</script><?php
        ?><script>document.location.href="view_image.php";</script><?php
}
    }
    ?>


<title>Input Images</title>
<form action="<?php $_SERVER[PHP_SELF]; ?>" method="post" enctype="multipart/form-data" name="form" target="_self" id="form">
<table width="63%" border="0" align="center" cellpadding="1" cellspacing="1">
  <tr>
    <td>Gambar</td>
    <td>:</td>
    <td colspan="3"><input name="gambar" type="file" id="gambar" size="30" maxlength="30" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td colspan="3"><input type="submit" name="simpan" id="simpan" value="Simpan" class="button"/></td>
  </tr>
</table>
</form>
Berikut adalah script view_image.php:
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>View Images</title>
  <?php
    mysql_connect("localhost","root","");   
    mysql_select_db("db_images");
    ?>
<?php
switch($_GET["act"]){
    case "del";
$id=$_GET['id'];
$qr=mysql_query("select * FROM tb_images WHERE id='$id'");
$r=mysql_fetch_array($qr);
$tempat_foto = 'img/'.$r['images'];
unlink("$tempat_foto");

$hapus=mysql_query("DELETE FROM tb_images WHERE id ='$id'") or die ('query gagal'.mysql_error());
if ($hapus){
        ?><script language="javascript">alert('Data Anda Berhasil Dihapus')</script><?php
        ?><script>document.location.href="view_image.php";</script><?php
    }
    break;
}
?>
</head>

<body>
<p></p>
<center><a href="input_image.php"> Input Images </a></center>
<br />
<table width="349" border="1" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td width="32">No</td>
    <td width="166"><div align="center">Gambar</div></td>
    <td colspan="2"><div align="center">Aksi</div></td>
  </tr>

    <?php
    $sql = mysql_query("SELECT * FROM tb_images ORDER BY id ASC")or die ("Error!".mysql_error());;
while($hs = mysql_fetch_array($sql)){
        $no++;
        $id=$hs['id'];
        $img=$hs['images'];
?>
  <tr>
    <td><? echo "$no"; ?></td>
    <td><center><img src='img/<? echo "$img";?>' title='Edit' width="150" height="120"/></center></td>
    <td width="70"><div align="center"><a href="edit_image.php?id=<? echo "$id"; ?>">Edit</div></td>
    <td width="71"><div align="center"><a href="view_image.php?act=del&id=<? echo "$id"; ?>">Hapus</div></td>
  </tr>
<?php
}
?>
</table>

</body>
</html>
Berikut ini adalah script edit_image.php:
 <?php
    mysql_connect("localhost","root","");   
    mysql_select_db("db_images");
   
    $id=$_GET['id'];
$sql = mysql_query("SELECT * FROM tb_images WHERE id='$id'")or die ("gagal query!".mysql_error());
while($hs = mysql_fetch_array($sql)){      
        $img=$hs['images'];
}
    ?>
<title>Input Images</title>
<form action="<?php $_SERVER[PHP_SELF]; ?>" method="post" enctype="multipart/form-data" name="form" target="_self" id="form">
<table width="63%" border="0" align="center" cellpadding="1" cellspacing="1">
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td colspan="3"><img src='img/<? echo "$img";?>' title='Edit' width="150" height="120"/></td>
  </tr>
  <tr>
    <td>Gambar</td>
    <td>:</td>
    <td colspan="3"><input name="gambar" type="file" id="gambar" size="30" maxlength="30" />
      <input name="x" type="hidden" id="x" value="<? echo "$img";?>" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td colspan="3"><input type="submit" name="update" id="update" value="Update" class="button"/></td>
  </tr>
</table>
</form>
<?
$x=$_POST['x'];
$foto         =$_FILES['gambar']['tmp_name'];
$foto_name     =$_FILES['gambar']['name'];
$acak        = rand(1,99);
$tujuan_foto = $acak.$foto_name;
$tempat_foto = 'img/'.$tujuan_foto;
       
if (isset($_POST['update'])){
if (!$foto==""){
    $buat_foto=$tujuan_foto;
    $d = 'img/'.$x;
    @unlink ("$d");
    copy ($foto,$tempat_foto);
}else{
    $buat_foto=$x;
}
            $qu=mysql_query("UPDATE tb_images SET
            images='$buat_foto'
            WHERE id='$id'")or die (mysql_error());
           
    ?><script language="javascript">alert("Data Berhasil Diupdate")</script><?
    ?><script>document.location='view_image.php';</script><?
    }
?>


Berdasarkan pengalaman saya selama ini, paling ribet itu ketika utak-atik dibagian edit. Dimana ketika foto/gambar diganti maka seharusnya foto/gambar lama yang ada di folder seharusnya hilang dan diganti dengan foto/gambar baru. Demikian juga ketika proses hapus. Seharusnya foto/gambar yang ada di folder juga terhapus, bukan hanya data yang ada di database saja yang terhapus. Tapi, pada tutorial ini semua work! hehehe.

Fin.
Happy Coding.
Alhamdulilah.
:)

10 comments:

  1. tetep ga ke hapus gambarnya

    ReplyDelete
  2. itu database gambarnya bertipe varchar kan ya, gimna kalau bertipe blob, apakah tetap sama syntaxnya seperti diatas atau beda? mohon pencerahannya

    ReplyDelete
  3. data yang ada pada database memang kehapus, tapi gambar/ file yang ada didalam folder gak ke apus gan, malah [function.unlink] permision denied

    ReplyDelete
  4. tapi masih muncul "notice" error ketika belum tekan update

    ReplyDelete
  5. tmp_name itu file yg dimana ? mhn dijawab ya min

    ReplyDelete
  6. Terimakasih.. tulisannya sangat bermanfaat..
    My blog
    My Campus

    ReplyDelete