Read 117 times | Created 2013-09-05 10:19:02 | Updated 2013-09-05 10:19:02 | | |

 

<?php 
/********************************* 
FILENAME  : checkbox.php 
CREATE BY : cahya dsn 
PURPOSE   : checkbox submitting form
CREATE DATE : 2013-09-05 
********************************** 
#table creation 

USE `test`; 

DROP TABLE IF EXISTS `t_buku`; 
CREATE TABLE IF NOT EXISTS `t_buku` ( 
 `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key untuk table t_buku', 
 `judul` varchar(50) NOT NULL COMMENT 'judul', 
 `pengarang` varchar(50) NOT NULL COMMENT 'pengarang', 
 `status` set('available','notAvailable') NOT NULL DEFAULT 'notAvailable',
 PRIMARY KEY(`id`)  
) ENGINE=MyISAM COMMENT='tabel untuk menyimpan data buku'; 

CREATE UNIQUE INDEX idx_judul_pengarang ON t_buku (`judul`, `pengarang`); 

INSERT INTO `t_buku`(`judul`,`pengarang`) 
VALUES ('judul1','pengarang1'), 
('judul2','pengarang2'), 
('judul3','pengarang3'), 
('judul4','pengarang1'), 
('judul5','pengarang2'), 
('judul6','pengarang1'), 
('judul7','pengarang3'); 
*/ 
?>
<!DOCTYPE hmtl>
<html>
  <head>
    <title>CHECKBOX</title>
  </head>
  <body>
<?php
$pengarang=isset($_GET['pengarang'])?$_GET['pengarang']:'';
$dbhost='localhost';
$dbuser='root';
$dbpass='';
$dbname='test';
$db=new mysqli($dbhost,$dbuser,$dbpass,$dbname);
if(empty($pengarang))
{
  $sql="SELECT DISTINCT pengarang FROM t_buku";
  if($result=$db->query($sql))
  {
    echo "Pilih Pengarang:<ul>";
    while($record=$result->fetch_object())
    {
      echo "<li><a href='?pengarang=".$record->pengarang."'>".$record->pengarang."</a></li>";
    }
    echo "</ul>";
  }
}
else
{
  if($_POST['submit'])
  {
    foreach($_POST['id'] as $index){
      if(isset($_POST['chk'.$index]))
      {
        $sql="UPDATE t_buku SET status='".$_POST['chk'.$index]."' WHERE id='".$index."'";
        if($db->query($sql))
        {
          echo "Data dengan id='".$index."' berhasil diupdate<br>";
        }
      }
    }
  }  
  ?>
    <form method="POST">
      <table>
        <tr>
          <th>No</th>
          <th>Judul</th>
          <th>Pengarang</th>
          <th>Status</th>
        </tr>
<?php
  $sql="SELECT * 
        FROM t_buku 
        WHERE status='notAvailable' AND pengarang='".$pengarang."'";
  if($result=$db->query($sql))
  {
    $no=0;
    while($record=$result->fetch_object())
    {
      echo "<tr>"
          ."<td>".(++$no)
          ."<input type='hidden' name='id[]' value='".$record->id."'/>"
          ."</td>"
          ."<td>".$record->judul."</td>"
          ."<td>".$record->pengarang."</td>"
          ."<td><input type='checkbox' name='chk".$record->id."' value='available' "
          .($record->status=='available'?" checked='checked'":"")."/></td>";
    }
  }
}
?>        
      </table>
      <br/>
      <input type="submit" name="submit" value="submit" /> | 
      <a href="<?php echo $_SERVER['PHP_SELF'];?>">kembali</a>
    </form>
  </body>
</html>