ทบทวน เพิ่ม ลบ แก้ไข เช็คฟอร์ม แบ่งหน้า อัพรูป ในโค้ดเดียว

เขียนเมื่อ 9 ปีก่อน โดย Ninenik Narkdee
อัพรูป php แก้ไข แบ่งหน้า ลบ เพิ่ม

คำสั่ง การ กำหนด รูปแบบ ตัวอย่าง เทคนิค ลูกเล่น การประยุกต์ การใช้งาน เกี่ยวกับ อัพรูป php แก้ไข แบ่งหน้า ลบ เพิ่ม

ดูแล้ว 34,842 ครั้ง




ตัวอย่างโค้ดต่อไปนี้เป้นแนวทาง หรือพื้นฐานสำหรับคนที่จำเป็นต้องใช้งาน
และจัดการโค้ดที่ติดต่อกับฐานข้อมูล บ่อยๆ เป็นประจำ โค้ดทั้งหมด มาจากเนื้อหา
ต่างๆ ในเว็บไซต์ ใช้งาน bootstrap css 
 
มีฟังก์ชั่น php ต่างๆ ที่ประยุกต์ใช้งาน เช่น 
ฟังก์ชั่นการแบ่งหน้า 
ฟังก์ชั่นการอัพโหลดรูป
 
มีการใช้งาน css เช่น
การใช้งาน bootstrap css
การปรับแต่งการแบ่งหน้า ด้วย css
 
มีรูปแบบการทำงานกับฐานข้อมูล เช่น
การแสดงข้อมูล
การบันทึกข้อมูล
การแก้ไขข้อมูล
การลบข้อมูล
การแบ่งหน้าข้อมูล
 
มีการใช้งาน jquery เช่น
การตรวจสอบฟอร์ม
การแสดงพรีวิวรูปก่อนอัพโหลด
 
มีรูปแบบฐานข้อมูลตัวอย่างประกอบ
 
ทั้งหมดรวมไว้ในไฟล์เดียว สามารถนำไปแยกและทำเป็น include
หรือเรียกใช้แบบ external ได้
 
รูปตัวอย่างผลลัพธ์ 
 
 
ตาราง db ฐานข้อมูลสำหรับทดสอบ
 
--
-- Table structure for table `tbl_user`
--

CREATE TABLE `tbl_user` (
  `user_id` int(11) NOT NULL,
  `user_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `user_pic` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_user`
--
ALTER TABLE `tbl_user`
  ADD PRIMARY KEY (`user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_user`
--
ALTER TABLE `tbl_user`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
 
โค้ดทั้งหมด
 
<?php
session_start();  
// โค้ดไฟล์ dbconnect.php ดูได้ที่ http://niik.in/que_2398_5642
require_once("dbconnect.php");  
$php_filename=basename($_SERVER['PHP_SELF']); // เก็บชื่อไฟล์ปัจจุบันไว้ในตัวแปร
?>
<?php
// ฟังก์ชั่นสำหรับอัพรูปภาพ ดูเพิ่มเติมได้ที่ 
// https://www.ninenik.com/content.php?arti_id=497
function uppic_only($img,$imglocate,$limit_size=2000000,$limit_width=0,$limit_height=0){
    $allowed_types=array("jpg","jpeg","gif","png");   
    if($img["name"]!=""){
        $fileupload1=$img["tmp_name"];
        $data_Img=@getimagesize($fileupload1);
        $g_img=explode(".",$img["name"]);
        $ext = strtolower(array_pop($g_img)); 
        $i_num=1;
        $file_up=time()."-".$i_num.".".$ext;        
        $canUpload=0;
        if(isset($data_Img) && $data_Img[0]>0 && $data_Img[1]>0){
            if($img["size"]<=$limit_size){               
                if($limit_width>0 && $limit_height>0){
                    if($data_Img[0]<=$limit_width && $data_Img[1]<=$limit_height){
                        $canUpload=1;
                    }                   
                }elseif($limit_width>0 && $limit_height==0){
                    if($data_Img[0]<=$limit_width){
                        $canUpload=1;
                    }       
                }elseif($limit_width==0 && $limit_height>0){
                    if($data_Img[1]<=$limit_height){
                        $canUpload=1;
                    }                                               
                }else{
                    $canUpload=1;                   
                }           
            }       
        }       
        if($fileupload1!="" && @in_array($ext,$allowed_types) && $canUpload==1){            
                @copy($fileupload1,$imglocate.$file_up);    
                @chmod($imglocate.$file_up,0777);                               
        }else{
            $file_up="";
        }
    }
    return $file_up; // ส่งกลับชื่อไฟล์
}
?>
<?php  
// ฟังก์ชั่นสำหรับการแบ่งหน้า NEW MODIFY  
// https://www.ninenik.com/content.php?arti_id=497
function page_navi($before_p,$plus_p,$total,$total_p,$chk_page){        
    global $urlquery_str;     
    $pPrev=$chk_page-1;     
    $pPrev=($pPrev>=0)?$pPrev:0;     
    $pNext=$chk_page+1;     
    $pNext=($pNext>=$total_p)?$total_p-1:$pNext;          
    $lt_page=$total_p-4;     
    if($chk_page>0){       
        echo "<a  href='$urlquery_str"."pages=".intval($pPrev+1)."' class='naviPN'>Prev</a>";     
    }     
    if($total_p>=11){     
        if($chk_page>=4){     
            echo "<a $nClass href='$urlquery_str"."pages=1'>1</a><a class='SpaceC'>. . .</a>";        
        }     
        if($chk_page<4){     
            for($i=0;$i<$total_p;$i++){       
                $nClass=($chk_page==$i)?"class='selectPage'":"";     
                if($i<=4){     
                echo "<a $nClass href='$urlquery_str"."pages=".intval($i+1)."'>".intval($i+1)."</a> ";        
                }     
                if($i==$total_p-1 ){      
                echo "<a class='SpaceC'>. . .</a><a $nClass href='$urlquery_str"."pages=".intval($i+1)."'>".intval($i+1)."</a> ";        
                }            
            }     
        }     
        if($chk_page>=4 && $chk_page<$lt_page){     
            $st_page=$chk_page-3;     
            for($i=1;$i<=5;$i++){     
                $nClass=($chk_page==($st_page+$i))?"class='selectPage'":"";     
                echo "<a $nClass href='$urlquery_str"."pages=".intval($st_page+$i+1)."'>".intval($st_page+$i+1)."</a> ";           
            }     
            for($i=0;$i<$total_p;$i++){       
                if($i==$total_p-1 ){      


                $nClass=($chk_page==$i)?"class='selectPage'":"";     
                echo "<a class='SpaceC'>. . .</a><a $nClass href='$urlquery_str"."pages=".intval($i+1)."'>".intval($i+1)."</a> ";        
                }            
            }                                        
        }        
        if($chk_page>=$lt_page){     
            for($i=0;$i<=4;$i++){     
                $nClass=($chk_page==($lt_page+$i-1))?"class='selectPage'":"";     
                echo "<a $nClass href='$urlquery_str"."pages=".intval($lt_page+$i)."'>".intval($lt_page+$i)."</a> ";        
            }     
        }             
    }else{     
        for($i=0;$i<$total_p;$i++){       
            $nClass=($chk_page==$i)?"class='selectPage'":"";     
            echo "<a href='$urlquery_str"."pages=".intval($i+1)."' $nClass  >".intval($i+1)."</a> ";        
        }            
    }        
    if($chk_page<$total_p-1){     
        echo "<a href='$urlquery_str"."pages=".intval($pNext+1)."'  class='naviPN'>Next</a>";     
    }     
}  
?>
<?php 
// เมื่กดปุ่ม เพื่อบันทุกข้อมูล
if(isset($_POST["bt_upload"])){
//  อัพโหลดรูปในโฟลเดอร์ชื่อ picup
//  ตัวอย่างการใช้งานแบบปกติ อัพรูปภาพขนาดไม่เกิน 2 MB
    $dataUpPic=uppic_only($_FILES["pic_upload"],"picup/");
    if(isset($_POST['h_user_id']) && $_POST['h_user_id']!=""){  // กรณีแก้ไขข้อมูล
        $full_pic_path="picup/".$_POST['h_user_pic'];
        if(file_exists($full_pic_path) && $_POST['h_user_pic']!=""){
            if($dataUpPic!=""){
                unlink($full_pic_path);
            }else{
                $dataUpPic=$_POST['h_user_pic'];   
            }
        }
		$sql_update="
			UPDATE tbl_user SET 
			user_name='".$_POST['name']."',
			user_pic='".$dataUpPic."'
			WHERE user_id='".$_POST['h_user_id']."'
		";
		$mysqli->query($sql_update); 
    }else{ // กรณีเพิ่มข้อมูล
		$sql_insert="
			INSERT INTO tbl_user(
				user_id,
				user_name,
				user_pic
			)VALUES(
				NULL,
				'".$_POST['name']."',
				'".$dataUpPic."'
			)
		";  
		$mysqli->query($sql_insert);				
    }
    header("Location:".$php_filename);
    exit;
}
?>
<?php
if(isset($_GET['d_user_id']) && $_GET['d_user_id']!=""){
	$sql = "
		SELECT * FROM tbl_user WHERE user_id='".$_GET['d_user_id']."'
	";
	$result = $mysqli->query($sql);
	if($result && $result->num_rows>0){  // คิวรี่ข้อมูลสำเร็จหรือไม่ และมีรายการข้อมูลหรือไม่
		$row = $result->fetch_assoc();
        $full_pic_path="picup/".$row['user_pic'];
        if(file_exists($full_pic_path) && $row['user_pic']!=""){
            unlink($full_pic_path);
        }		
		$sql_delete="
			DELETE FROM tbl_user WHERE user_id='".$_GET['d_user_id']."'
		";
		$mysqli->query($sql_delete);
    }
    header("Location:".$php_filename);
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="bootstrap/css/bootstrap.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <style type="text/css">  
        #thumbnail img{height:100px;margin:5px;}  
        canvas{border:1px solid red;}      
    </style>   
    <style type="text/css">  
    /* css แบ่งหน้า */ 
    .browse_page{     
        clear:both;     
        margin-left:12px;     
        height:25px;     
        margin-top:5px;     
        display:block;     
    }     
    .browse_page a,.browse_page a:hover{     
        display:block;     
        width: 2%;  
        font-size:14px;     
        float:left;     
        margin:0px 5px;  
        border:1px solid #CCCCCC;     
        background-color:#F4F4F4;     
        color:#333333;     
        text-align:center;     
        line-height:22px;     
        font-weight:bold;     
        text-decoration:none;     
        -webkit-border-radius: 5px;  
        -moz-border-radius: 5px;  
        border-radius: 5px;   
    }     
    .browse_page a:hover{     
        border:1px solid #CCCCCC;  
        background-color:#999999;  
        color:#FFFFFF;     
    }     
    .browse_page a.selectPage{     
        display:block;     
        width:45px;     
        font-size:14px;     
        float:left;     
        margin-right:2px;     
        border:1px solid #CCCCCC;  
        background-color:#999999;  
        color:#FFFFFF;     
        text-align:center;     
        line-height:22px;      
        font-weight:bold;     
        -webkit-border-radius: 5px;  
        -moz-border-radius: 5px;  
        border-radius: 5px;   
    }     
    .browse_page a.SpaceC{     
        display:block;     
        width:45px;     
        font-size:14px;     
        float:left;     
        margin-right:2px;     
        border:0px dotted #0A85CB;     
        background-color:#FFFFFF;     
        color:#333333;     
        text-align:center;     
        line-height:22px;     
        font-weight:bold;     
        -webkit-border-radius: 5px;  
        -moz-border-radius: 5px;  
        border-radius: 5px;   
    }     
    .browse_page a.naviPN{     
        width:50px;     
        font-size:12px;     
        display:block;     
    /*    width:25px;   */ 
        float:left;     
        border:1px solid #CCCCCC;  
        background-color:#999999;  
        color:#FFFFFF;     
        text-align:center;     
        line-height:22px;     
        font-weight:bold;        
        -webkit-border-radius: 5px;  
        -moz-border-radius: 5px;  
        border-radius: 5px;   
    }    
    /* จบ css แบ่งหน้า */ 
    </style>         
</head>
<body>
     
<br>
<?php
if(isset($_GET['e_user_id']) && $_GET['e_user_id']!=""){
    $edit_mode=1;
	$sql = "
	    SELECT * FROM tbl_user WHERE user_id='".$_GET['e_user_id']."'
	";
	$result = $mysqli->query($sql);
	if($result && $result->num_rows>0){  // คิวรี่ข้อมูลสำเร็จหรือไม่ และมีรายการข้อมูลหรือไม่
		$row = $result->fetch_assoc();	
        $edit_user_id=$row['user_id'];
        $edit_user_name=$row['user_name'];
        $edit_user_pic=$row['user_pic'];
    }
}
?>
<div style="margin:auto;width:80%;">
<h3> บันทึกข้อมูล</h3>     
<form class="form" id="myFrom" method="post" action=""  role="form" enctype="multipart/form-data">      
    <div class="form-group has-feedback">    
       <lable class="control-label">Name : </lable>    
        <input type="text" autocomplete="off" class="form-control css-require" name="name" 
        value="<?=(isset($edit_user_name))?$edit_user_name:""?>">    
        <span class="glyphicon form-control-feedback" aria-hidden="true"></span>  
    </div>    
    <div class="form-group">    
       <lable class="control-label">Picture : </lable>    
       <input id="file_upload" style="display:none" name="pic_upload" type="file" >    
    <div id="upload" class="btn btn-info">  
       Upload File  
    </div>  
    <div id="thumbnail"></div>                 
    </div>  
    <input type="hidden" name="h_user_id" value="<?=(isset($edit_user_id))?$edit_user_id:""?>">  
    <input type="hidden" name="h_user_pic" value="<?=(isset($edit_user_pic))?$edit_user_pic:""?>">
 
    <a href="<?=$php_filename?>" class="btn btn-default">ยกเลิก</a>   
    &nbsp;&nbsp;
    <button type="submit" name="bt_upload" class="btn btn-primary">บันทึกข้อมูล</button>   
</form>    
<br>    
<br><br>
<table class="table table-bordered table-condensed">
    <tr class="active">
        <th width="50" class="text-center">#</th>
        <th>Name</th>
        <th width="150" class="text-center">Mange</th>
    </tr>
<?php
    // ส่วนของการแสดงข้อมูล จากฐานข้อมูล สนใจเรื่องแบ่งหน้าดูได้ที่
    // 
    $i=0;
	$sql = "
	    SELECT * FROM tbl_user 
	";
	$result = $mysqli->query($sql);
	$total = ($result)?$result->num_rows:0;

    $e_page=2; // กำหนด จำนวนรายการที่แสดงในแต่ละหน้า     
    if(!isset($_GET['pages'])){     
        $_GET['pages']=0;     
		$chk_page = 0;
    }else{     
        $_GET['pages']=$_GET['pages']-1;  
        if($_GET['pages']<0){  
            $_GET['pages']=0;     
        }  
        $chk_page=$_GET['pages'];       
        $_GET['pages']=$_GET['pages']*$e_page;     
    }     
    $sql.=" ORDER BY user_id  LIMIT ".$_GET['pages'].",$e_page";  
 
    $result = $mysqli->query($sql);
	if($result && $result->num_rows>=1){ 
        $plus_p=($chk_page*$e_page) + $result->num_rows;     
    }else{     
        $plus_p=($chk_page*$e_page);         
    }     
    $total_p=ceil($total/$e_page);     
    $before_p=($chk_page*$e_page)+1;    
    /// END PAGE NAVI ZONE       
    while($row = $result->fetch_assoc()){
    $i++;
?>
    <tr>
        <td class="text-center"><?=$i?></td>
        <td>
        <?=$row['user_name']?>
        [ <img src="picup/<?=$row['user_pic']?>" style="height:20px;"> <?=$row['user_pic']?>]
        </td>
        <td class="text-center">
 
             
             
    <a href="?e_user_id=<?=$row['user_id']?>" class="btn btn-success btn-xs" >
    <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
    </a>
    &nbsp;&nbsp;
    <a href="?d_user_id=<?=$row['user_id']?>" class="btn btn-danger btn-xs btn-remove" >
      <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
    </a>
        
        </td>
    </tr>
<?php } ?> 
    
</table>
 
<div style="margin:auto;width:100%;">  
  <?php if($total>$e_page){ ?>                    
  <div class="browse_page">     
    <?php        
    if(count($_GET)<=1){  
        $urlquery_str="?";  
    }else{  
        $para_get="";  
        foreach($_GET as $key=>$value){  
            if($key!="pages"){  
                $para_get.=$key."=".$value."&";  
            }  
        }  
        $urlquery_str="?$para_get";  
    }  
    // เรียกใช้งานฟังก์ชั่น สำหรับแสดงการแบ่งหน้า        
    page_navi($before_p,$plus_p,$total,$total_p,$chk_page);         
    ?>  
    </div>     
    <?php } ?>    
</div>      
 
<br />
 
</div>   
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>    
<script type="text/javascript" >  
$(function () {  
   
    // ส่วนของการถามยืนยันการลบข้อมูล
    $(".btn-remove").on("click",function(){
       if(confirm("ยืนยันการลบข้อมูล?")){
            
       }else{
        return false;   
       }
    });
     
    // ส่วนของการซ่อนแสดง input file เมื่อคลิกที่ปุ่มที่เรากำหนด
    $("#upload").on("click",function(e){  
        $("#file_upload").show().click().hide();  
        e.preventDefault();  
    });  
     
    // ส่วนของการแสดงรูปพรีวิวเมื่อมีการเปลี่ยนแปลง
    $("#file_upload").on("change",function(e){  
        var files = this.files  
        showThumbnail(files)          
    });  
   
     
    // ส่วนของการแสดงรูปพรีวิวก่อนอัพโหลด
    function showThumbnail(files){  
   
        $("#thumbnail").html("");  
        for(var i=0;i<files.length;i++){  
            var file = files[i]  
            var imageType = /image.*/  
            if(!file.type.match(imageType)){  
                //     console.log("Not an Image");  
                continue;  
            }  
   
            var image = document.createElement("img");  
            var thumbnail = document.getElementById("thumbnail");  
            image.file = file;  
            thumbnail.appendChild(image)  
   
            var reader = new FileReader()  
            reader.onload = (function(aImg){  
                return function(e){  
                    aImg.src = e.target.result;  
                };  
            }(image))  
   
            var ret = reader.readAsDataURL(file);  
            var canvas = document.createElement("canvas");  
            ctx = canvas.getContext("2d");  
            image.onload= function(){  
                ctx.drawImage(image,100,100)  
            }  
        } // end for loop  
   
    } // end showThumbnail  
   
   
    // ส่วนของการเช็ค ฟอร์ม ก่อน submit ดูเพิ่มเติมได้ที่ 
    // https://www.ninenik.com/content.php?arti_id=579 via @ninenik
     var obj_check=$(".css-require");  
     $("#myFrom").on("submit",function(){  
         obj_check.each(function(i,k){  
             var status_check=0;  
             if(obj_check.eq(i).find(":radio").length>0 || obj_check.eq(i).find(":checkbox").length>0){  
                 status_check=(obj_check.eq(i).find(":checked").length==0)?0:1;      
             }else{  
                 status_check=($.trim(obj_check.eq(i).val())=="")?0:1;  
             }  
             formCheckStatus($(this),status_check);        
         });  
         if($(this).find(".has-error").length>0){  
              return false;  
         }  
     });  
        
     obj_check.on("change",function(){  
         var status_check=0;  
         if($(this).find(":radio").length>0 || $(this).find(":checkbox").length>0){  
             status_check=($(this).find(":checked").length==0)?0:1;      
         }else{  
             status_check=($.trim($(this).val())=="")?0:1;  
         }  
         formCheckStatus($(this),status_check);         
     });  
        
     var formCheckStatus = function(obj,status){  
         if(status==1){  
             obj.parent(".form-group").removeClass("has-error").addClass("has-success");  
             obj.next(".glyphicon").removeClass("glyphicon-warning-sign").addClass("glyphicon-ok");      
         }else{  
             obj.parent(".form-group").removeClass("has-success").addClass("has-error");  
             obj.next(".glyphicon").removeClass("glyphicon-ok").addClass("glyphicon-warning-sign");        
         }  
     }      
     
     
});  
 </script>        
</body>
</html>
 
ในโค้ดจะไม่ได้อธิบายรายละเอียดมาก เนื่องจากเป็นส่วนที่เคยแนะนำแล้วในเว็บไซต์
สามารถค้นหารายละเอียดเพิ่มเติม ได้ที่ช่องคนหาด้านบน  
หากเข้าใจการทำงาน ของโค้ดด้านบน ก็สามารถเอาไปประยุกต์ใช้งานได้อย่างหลากหลาย


กด Like หรือ Share เป็นกำลังใจ ให้มีบทความใหม่ๆ เรื่อยๆ น่ะครับ







เนื้อหาที่เกี่ยวข้อง






เนื้อหาพิเศษ เฉพาะสำหรับสมาชิก

กรุณาล็อกอิน เพื่ออ่านเนื้อหาบทความ

ยังไม่เป็นสมาชิก

สมาชิกล็อกอิน



( หรือ เข้าใช้งานผ่าน Social Login )




URL สำหรับอ้างอิง





คำแนะนำ และการใช้งาน

สมาชิก กรุณา ล็อกอินเข้าระบบ เพื่อตั้งคำถามใหม่ หรือ ตอบคำถาม สมาชิกใหม่ สมัครสมาชิกได้ที่ สมัครสมาชิก


  • ถาม-ตอบ กรุณา ล็อกอินเข้าระบบ
  • เปลี่ยน


    ( หรือ เข้าใช้งานผ่าน Social Login )







เว็บไซต์ของเราให้บริการเนื้อหาบทความสำหรับนักพัฒนา โดยพึ่งพารายได้เล็กน้อยจากการแสดงโฆษณา โปรดสนับสนุนเว็บไซต์ของเราด้วยการปิดการใช้งานตัวปิดกั้นโฆษณา (Disable Ads Blocker) ขอบคุณครับ