티스토리 뷰

반응형

웹사이트에 사진등록을 위한 버튼을 만들고, 서버에서 처리하는 방법과 javascript와 제이쿼리 등을 이용해서 실제 서버에 파일을 업로드 하고, mysql로 DB에 이러한 내용을 저장하고 삭제하는 것까지 구현해 봅시다.

실제 웹사이트에 구현한 버튼.... 출고전 사진등록을 누르면 실제 작동하는 코드를 만들어 봤습니다.

버튼 제작 (bootstrap을 이용해서 간단하게 만듬)

<button  id="regpicBtn" type="button" class="btn btn-success btn-lg btn-lg " > 출고전 사진등록  </button>&nbsp;&nbsp;&nbsp;

 // 버튼을 눌렀을때 동작하는 구문
 <script language="javascript">
$(document).ready(function(){
	$("#regpicBtn").click(function(){    // 사진등록
	  const num = $("#num").val();
	  window.open('reg_pic.php?num=' + num ,"출고전 사진등록","width=1200, 
      height=700, top=0,left=0,scrollbars=no");
		 });
});
</script>

버튼을 누르면 reg_pic.php로 이동해서 화면에 창을 띄우고 파일을 선택하는 루틴을 만듭니다.

<meta charset="utf-8">
 
 <?php
 session_start(); 
  
 $num=$_REQUEST["num"]; 
 $parent=$num;
 
  if(isset($_REQUEST["check"])) 
	 $check=$_REQUEST["check"]; 
   else
     $check=$_POST["check"]; 
 
 require_once("../lib/mydb.php");
 $pdo = db_connect();
 
 try{
     $sql = "select * from (자신이 사용하는 DB) where num=?";
     $stmh = $pdo->prepare($sql);  
     $stmh->bindValue(1, $num, PDO::PARAM_STR);      
     $stmh->execute();            
      
     $row = $stmh->fetch(PDO::FETCH_ASSOC); 	 
  
     $PROD_DES = $row["PROD_DES"];
					
     }catch (PDOException $Exception) {
       print "오류: ".$Exception->getMessage();
     }  	 

if(isset($_POST['submit'])){
    $countfiles = count($_FILES['file']['name']);
    for($i=0;$i<$countfiles;$i++){
        $filename = $_FILES['file']['name'][$i];
        $sql = "INSERT INTO fileup(id,name) VALUES ('$filename','$filename')";
        $db->query($sql);
        move_uploaded_file($_FILES['file']['tmp_name'][$i],'imgwork/'.$filename);
    }
}
?>

 <!DOCTYPE HTML>
 <html>
 <head> 
 <meta charset="utf-8">
 <head>
 <meta charset="UTF-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<link rel="stylesheet" href="../css/partner.css" type="text/css" />

<style>

.progress {
  margin: 10px;
  width: 700px;
}

.blink {
	-webkit-animation: blink 1.05s linear infinite;
	-moz-animation: blink 1.05s linear infinite;
	-ms-animation: blink 1.05s linear infinite;
	-o-animation: blink 1.05s linear infinite;
	 animation: blink 1.05s linear infinite;
}
@-webkit-keyframes blink {
	0% { opacity: 1; }
	50% { opacity: 1; }
	50.01% { opacity: 0; }
	100% { opacity: 0; }
}
@-moz-keyframes blink {
	0% { opacity: 1; }
	50% { opacity: 1; }
	50.01% { opacity: 0; }
	100% { opacity: 0; }
}
@-ms-keyframes blink {
	0% { opacity: 1; }
	50% { opacity: 1; }
	50.01% { opacity: 0; }
	100% { opacity: 0; }
}
@-o-keyframes blink {
	0% { opacity: 1; }
	50% { opacity: 1; }
	50.01% { opacity: 0; }
	100% { opacity: 0; }
}
@keyframes blink {
	0% { opacity: 1; }
	50% { opacity: 1; }
	50.01% { opacity: 0; }
	100% { opacity: 0; }
}
</style>

 <title> 사진등록/수정 </title>
 </head>
  <body>
<div id="top-menu">

</div>
</div>
<br> 
			<div class="row">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
			<h1 class="display-1  text-left">
  <input type="button" class="btn btn-secondary btn-lg " value="닫기" onclick="self.close();"> </h1> 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  </div>
<br>
<br>
<form id="board_form" name="board_form" method="post" action="pic_insert.php"   enctype="multipart/form-data">  
     
	 <input type="hidden" id=childnum name=childnum value="<?=$childnum?>" >
	 <input type="hidden" id=check name=check value="<?=$check?>" >
	 <input type="hidden" id=parent name=parent value="<?=$parent?>" >
	 <input type="hidden" id=num name=num value="<?=$num?>" >
	 <input type="hidden" id=mode name=mode value="<?=$mode?>" >
	 <input type="hidden" id=PROD_DES name=PROD_DES value="<?=$PROD_DES?>" >
	 <div  class="container">
			<div class="row">

	 <H1  class="display-5 font-center text-center" > 사진 등록/수정 </H1> 
 </div>
 
 			<div class="row">				
			   <div id=progressbar class="blink" style="display:none;">
			 <!--  <div id=progressbar style="display:none;" class=blinking > -->
			   <div class="row">				 </div> <br>
					<h1 class="display-1  text-left"> 사진등록을 서버에 저장중입니다. <br> (잠시만 기다려주세요.) </h1>
					<div class="progress">
					  <div id="dynamic" class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
						<span id="current-progress"></span>
					  </div>
				   	</div>			
								<div class="row">				 </div> <br>
				</div>
			</div>
			
			<br>
			<div class="row">
		     <h1 class="display-5 font-center text-left"> 		   
					품명(규격) :   <?=$PROD_DES?> 	   
			<br> 
			<br> 
		<?php 
			if($filename1!=null) {
			  print "기존 업로드 파일 있음 " . $filename1 ;  
			  echo "<img src='". $imgurl1  . "'";
			  			  print " </div> <br> <br>";
			  }
			?>
		  <div class="row">
		  <input id="upfile"  name="upfile[]" class="input" type="file" onchange="this.value" multiple >
		  
	   </div>	    	

 			<div class="row">				
			   <div id=progressbar1 class="blink" style="display:none;">
			 <!--  <div id=progressbar style="display:none;" class=blinking > -->
			   <div class="row">				 </div> <br>
					<h1 class="display-1  text-left"> 사진등록을 서버에 저장중입니다. <br> (잠시만 기다려주세요.) </h1>
					<div class="progress">
					  <div id="dynamic" class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
						<span id="current-progress"></span>
					  </div>
				   	</div>			
					
								<div class="row">				 </div> <br>
				</div>
			</div>   	   
	   	   							
		<div class="row">

		         <h1 class="display-5 font-center text-left"> 		   
       
						<br>
  
			<div class="row">							
			<h1 class="display-1  text-left">
  <input type="button" class="btn btn-primary btn-lg " value="서버에 저장하기" onclick="javascript:pro_submit()" > </h1>

	   </div>	    		
   
	   </div> 

 </div> 
 </form>
	 
 </body>
</html>    

<script> 
var imgObj = new Image();
function showImgWin(imgName) {
imgObj.src = imgName;
setTimeout("createImgWin(imgObj)", 100);
}
function createImgWin(imgObj) {
if (! imgObj.complete) {
setTimeout("createImgWin(imgObj)", 100);
return;
}
imageWin = window.open("", "imageWin",
"width=" + imgObj.width + ",height=" + imgObj.height);
}

   function inputNumberFormat(obj) { 
    obj.value = comma(uncomma(obj.value)); 
} 
function comma(str) { 
    str = String(str); 
    return str.replace(/(\d)(?=(?:\d{3})+(?!\d))/g, '$1,'); 
} 
function uncomma(str) { 
    str = String(str); 
    return str.replace(/[^\d]+/g, ''); 
}

function input_Text(){
    document.getElementById("test").value = comma(Math.floor(uncomma(document.getElementById("test").value)*1.1));   // 콤마를 계산해 주고 다시 붙여주고
}  

function copy_below(){	   
}  

function pro_submit()
     {
		 
           $('#progressbar').show();	
           $('#progressbar1').show();	
           $('#progressbar2').show();	
           $('#board_form').submit();	

     }

</script>

위의 코드로 실행하면 아래와 같이 화면 뜹니다.

 

파일을 선택하고 '서버에 저장하기'버튼을 누르면 처리하는 루틴은 아래와 같습니다.

소스코드의 DB는 사용하시는 DB명으로 넣으면 됩니다.

 <?php session_start();  

 if(isset($_REQUEST["num"]))
    $num=$_REQUEST["num"];
		 else 
			$num="";			
 
  if(isset($_REQUEST["check"])) 
	 $check=$_REQUEST["check"]; 
   else
     $check=$_POST["check"]; 			


$countfiles = count($_FILES['upfile']['name']);
for($i=0;$i<$countfiles;$i++){
	$filename = $_FILES['upfile']['name'][$i];
//	$target_file = 'imgceiling/'.$filename;
//	move_uploaded_file($_FILES['file']['tmp_name'][$i],$target_file);
//	$statement->execute(array($filename,$target_file));
print $filename;
if($filename !='') {   			
	//Auth key
	define('UPLOAD_ERR_INI_SIZE',"100000000");

    $uploads_dir = './imgceiling'; //업로드 폴더 -현재 처리하는 폴더 하부로 imgtest 폴더
    $allowed_ext = array('jpg','jpeg','png','gif','JPG','JPEG','PNG','GIF'); //이미지 파일만 허용
 
 
 	//첨부파일이 있다면
	$uploadSize = 100000000;
	@mkdir("$upload_dir", 0707);
  	@chmod("$upload_dir", 0707);
	
  	// 올라간 파일의 퍼미션을 변경합니다.
  	chmod("$uploads_dir", 0755);

    // 변수 정리
    $error = $_FILES['upfile']['name'][$i];
    $name = $_FILES['upfile']['name'][$i];     
    $tmpNm =  explode( '.', $name );
    $ext = strtolower(end($tmpNm));

     echo "$ext <br>";
    // 확장자 확인
    if( !in_array($ext, $allowed_ext) ) {
        echo "허용되지 않는 확장자입니다.";
        exit;
    }
	
	
   // $newfile=$tmpNm[0].".".$ext ;
	$new_file_name = date("Y_m_d_H_i_s");
	$newfilename1 = $new_file_name."_" . $i . "." . $ext;      
    $url1 = $uploads_dir.'/'.$newfilename1; //올린 파일 명 그대로 복사해라.  시간초 등으로 파일이름 만들기
	
	// 사진회전시키기
	    
     $tmpimage = imagecreatefromjpeg($url1);
	 $exif = exif_read_data($url1);
	 
	 print '사진 정보' . $exif['Orientation'] . "<br>";
	 
			if(!empty($exif['Orientation']))
				{
					switch($exif['Orientation'])
					{
						case 8:
							$url1 = imagerotate($url1,90,0);
							break;
						case 3:
							$url1 = imagerotate($url1,180,0);
							break;
						case 6:
							$url1 = imagerotate($url1,-90,0);
							break;

					}
				}


	//요기부분 수정했습니다.
	$filename1 = compress_image($_FILES['upfile']["tmp_name"][$i], $url1, 70); //실제 파일용량 줄이는 부분

	list($width, $height, $type, $attr) = getImagesize($_FILES['upfile']["tmp_name"][$i]);
	echo $width."<br>";
	echo $height."<br>";
	echo $type."<br>";
	echo $attr."<br>";

	if($width > 700){
	 $switch_s=80;
	}else{
	 $switch_s=100;
	}
    $buffer = file_get_contents($url1);
 
    // 파일 정보 출력
    echo "<h2>파일 정보</h2> <h1>
        <ul>
            <li>자료번호: $num</li>
            <li>파일명: $name</li>
            <li>확장자: $ext</li>
            <li>url: {$url1}</li>
            <li>filename: {$filename1}</li>
        </ul> </h1>";
    
	$re_image = new Image($filename1);
	$rate=$width/$height;
	if($width>$height) {
			$re_image -> width(800);
			$re_image -> height(800/$rate);
		}
        else
		{
			$re_image -> width(800*$rate);
			$re_image -> height(800);
		}
		$re_image -> save();

		 require_once("../lib/mydb.php");
		 $pdo = db_connect();
     // insert
		try{		 
			$pdo->beginTransaction();   
			$sql = "insert into (사용하는DB.table명) ";
			$sql .=" (parentnum, picname) " ;        
			$sql .=" values(?, ?) " ;        
			   
			 $stmh = $pdo->prepare($sql); 

			 $stmh->bindValue(1, $num, PDO::PARAM_STR);             
			 $stmh->bindValue(2, $newfilename1, PDO::PARAM_STR);   
			 
			 $stmh->execute();
			 $pdo->commit(); 
				} catch (PDOException $Exception) {
				   $pdo->rollBack();
				   print "오류: ".$Exception->getMessage();
			 }  	
 
 
class Image {    
    var $file;
    var $image_width;
    var $image_height;
    var $width;
    var $height;
    var $ext;
    var $types = array('','gif','jpeg','png','swf');
    var $quality = 70;
    var $top = 0;
    var $left = 0;
    var $crop = false;
    var $type;
    
    function __construct($name='') {
        $this->file = $name;
        $info = getimagesize($name);
        $this->image_width = $info[0];
        $this->image_height = $info[1];
        $this->type = $this->types[$info[2]];
        $info = pathinfo($name);
        $this->dir = $info['dirname'];
        $this->name = str_replace('.'.$info['extension'], '', $info['basename']);
        $this->ext = $info['extension'];
    }
    
    function dir($dir='') {
        if(!$dir) return $this->dir;
        $this->dir = $dir;
    }
    
    function name($name='') {
        if(!$name) return $this->name;
        $this->name = $name;
    }
    
    function width($width='') {
        $this->width = $width;
    }
    
    function height($height='') {
        $this->height = $height;
    }
    
    function resize($percentage=50) {
        if($this->crop) {
            $this->crop = false;
            $this->width = round($this->width*($percentage/100));
            $this->height = round($this->height*($percentage/100));
            $this->image_width = round($this->width/($percentage/100));
            $this->image_height = round($this->height/($percentage/100));
        } else {
            $this->width = round($this->image_width*($percentage/100));
            $this->height = round($this->image_height*($percentage/100));
        }
        
    }
    
    function crop($top=0, $left=0) {
        $this->crop = true;
        $this->top = $top;
        $this->left = $left;
    }
    
    function quality($quality=70) {
        $this->quality = $quality;
    }
    
    function show() {
        $this->save(true);
    }
    
    function save($show=false) {
 
        if($show) @header('Content-Type: image/'.$this->type);
        
        if(!$this->width && !$this->height) {
            $this->width = $this->image_width;
            $this->height = $this->image_height;
        } elseif (is_numeric($this->width) && empty($this->height)) {
            $this->height = round($this->width/($this->image_width/$this->image_height));
        } elseif (is_numeric($this->height) && empty($this->width)) {
            $this->width = round($this->height/($this->image_height/$this->image_width));
        } else {
            if($this->width<=$this->height) {
                $height = round($this->width/($this->image_width/$this->image_height));
                if($height!=$this->height) {
                    $percentage = ($this->image_height*100)/$height;
                    $this->image_height = round($this->height*($percentage/100));
                }
            } else {
                $width = round($this->height/($this->image_height/$this->image_width));
                if($width!=$this->width) {
                    $percentage = ($this->image_width*100)/$width;
                    $this->image_width = round($this->width*($percentage/100));
                }
            }
        }
        
        if($this->crop) {
            $this->image_width = $this->width;
            $this->image_height = $this->height;
        }
 
        if($this->type=='jpeg') $image = imagecreatefromjpeg($this->file);
        if($this->type=='png') $image = imagecreatefrompng($this->file);
        if($this->type=='gif') $image = imagecreatefromgif($this->file);
        
        $new_image = imagecreatetruecolor($this->width, $this->height);
        imagecopyresampled($new_image, $image, 0, 0, $this->top, $this->left, $this->width, $this->height, $this->image_width, $this->image_height);
        
        $name = $show ? null: $this->dir.DIRECTORY_SEPARATOR.$this->name.'.'.$this->ext;
    
        if($this->type=='jpeg') imagejpeg($new_image, $name, $this->quality);
        if($this->type=='png') imagepng($new_image, $name);
        if($this->type=='gif') imagegif($new_image, $name);
 
        imagedestroy($image); 
        imagedestroy($new_image);
        
    }
    
}			 

// 파일 압축 메소드 
    function compress_image($source, $destination, $quality) { 
        $info = getimagesize($source); 
        if ($info['mime'] == 'image/jpeg') 
            $image = imagecreatefromjpeg($source); 
        elseif ($info['mime'] == 'image/gif') 
            $image = imagecreatefromgif($source); 
        elseif ($info['mime'] == 'image/png') 
            $image = imagecreatefrompng($source); 

     elseif ($info['mime'] == 'image/x-ms-bmp') 
      $image = imagecreatefrombmp($source);

        imagejpeg($image, $destination, $quality); 
        return $destination;
    }

echo "<script> opener.document.getElementById('pInput').value='100'; </script>";   // 부모창에 100 기록해보기
echo "<script> self.close(); </script>";   // 창닫기

?>

파일의 용량을 1Mbytes 이하로 줄여주는 루틴도 있으니, 필요하신 분은 참고해 주세요.

하단의 코드 opener는 부모창에 알려주는 역할을 하는 분입니다. 

mysql 테이블을 생성해서 추가하는 파일의 DB를 서버에 보관합니다.

create table ceilpicfile select * from espicfile ;
ALTER TABLE ceilpicfile ADD PRIMARY KEY(num);
Alter table ceilpicfile modify num int auto_increment;
사진데이터를 저장하는 mysql 테이블 생성함.

기존의 pic테이블이 있어 복사한 것인데, mysql에서 그냥 처음부터 생성해도 됩니다. 테이블에 필드가 생겨났습니다. 

화면을 보여주는 view.php에 자바스크립트 내용을 추가해서 화면에 사진이 나오게 변경합니다.

$(document).ready(function(){
	
	$("#pInput").val('50'); // 최초화면 사진파일 보여주기	

	 let timer3 = setInterval(() => {  // 2초 간격으로 사진업데이트 체크한다.
	      if($("#pInput").val()=='100')   // 사진이 등록된 경우
		  {
	             displayPicture(); 			
		  }	      
		  if($("#pInput").val()=='50')   // 사진이 등록된 경우
		  {
	             displayPictureLoad();				 
		  }		
	 }, 2000);	
	
	
	$("#regpicBtn").click(function(){    // 사진등록
	  const num = $("#num").val();
	  window.open('reg_pic.php?num=' + num ,"출고전 사진등록","width=1200, height=700,
           top=0,left=0,scrollbars=no");
		 });
});

 

pInput은 자식창에서 부모창으로 전달된 값으로 화면 출력여부를 정하기 위해서 만든 변수입니다.

<div id = "displayPicture" style="display:none;" > </div> 

본문의 이 부분에 사진이 나오는 것입니다.

사진을 보여주기 위해 작성한 자바스크립트(제이쿼리) 구문입니다.

	function displayPicture() {        // 첨부파일 형식으로 사진 불러오기
		$('#displayPicture').show();
		params = $("#num").val();	
		console.log($("#num").val());
        $.ajax({
        url:'loadpic.php?num='+params ,
        type:'post',
        data: $("mainFrm").serialize(),
        dataType: 'json',
        }).done(function(data){						
        const recnum = data["recnum"];		   
        console.log(data);
        $("#displayPicture").html('');
        for(i=0;i<recnum;i++) {			   
        $("#displayPicture").append("<img id=pic" + i + " src ='imgceiling/" + data["img_arr"][i] + "'> " );			   
        $("#displayPicture").append("&nbsp;<button type='button' class='btn btn-secondary' id='delPic" + i + "' onclick=delPicFn('" + i + "','" +  data["img_arr"][i] + "')> 삭제 </button>&nbsp;");					   
        }		   
        $("#pInput").val('');			
		});	
	}

	function displayPictureLoad() {    // 이미 있는 파일 불러오기
		$('#displayPicture').show();
		var picNum = "<? echo $picNum; ?>"; 					
		var picData = <?php echo json_encode($picData);?> ;	
		for(i=0;i<picNum;i++) {
		   $("#displayPicture").append("<img id=pic" + i + " src ='imgceiling/" + picData[i] + "'> " );			
		   $("#displayPicture").append("&nbsp;<button type='button' class='btn btn-secondary' id='delPic" + i + "' onclick=delPicFn('" + i + "','" + picData[i] + "')> 삭제 </button>&nbsp;");		
		   
		  }		   
			$("#pInput").val('');	
	}
		  
	delPicFn = function(divID, delChoice) {
		console.log(divID, delChoice);

		$.ajax({
			url:'delpic.php?picname=' + delChoice ,
			type:'post',
			data: $("mainFrm").serialize(),
			dataType: 'json',
			}).done(function(data){						
			   const picname = data["picname"];		   
			   console.log(data);
				$("#pic" + divID).remove();  // 그림요소 삭제
				$("#delPic" + divID).remove();  // 그림요소 삭제

			   $("#pInput").val('');			
			});		

	}

 

loadpic.php는 DB 테이블의 파일명을 읽어서 화면에 불러오기 위한 파일입니다.

delpic.php는 DB의 테이블의 파일정보를 삭제하고, 또한 서버에 업로드된 파일을 지워줍니다.

이렇게 해야 전체적인 프로세스가 끝납니다. 생각보다 코드가 길게 나오네요. 

delpic.php 소스코드

<?php
//delpic.php
header("Content-Type: application/json");  //json을 사용하기 위해 필요한 구문

isset($_REQUEST["picname"])  ? $picname=$_REQUEST["picname"] :   $picname=''; 

require_once("../lib/mydb.php");
$pdo = db_connect();	

// 물리적 자료를 지워주고, DB를 지워준다.
  
   $upload_dir = './imgceiling/';    //물리적 저장위치   
   $made_name = $upload_dir . $picname;
   unlink($made_name); 
    
   try{									
     $pdo->beginTransaction();
     $sql = "delete from (자신의 DB테이블명) where picname = ?";  
     $stmh = $pdo->prepare($sql);
     $stmh->bindValue(1,$picname,PDO::PARAM_STR);      
     $stmh->execute();  

     $pdo->commit();
	 
     } catch (Exception $ex) {
        $pdo->rollBack();
        print "오류: ".$Exception->getMessage();
   } 

//각각의 정보를 하나의 배열 변수에 넣어준다.
$data = array(
	"picname"=>           $picname,
);   
//json 출력
echo(json_encode($data, JSON_UNESCAPED_UNICODE));

?>

 

loadpic.php의 소스코드 (DB에서 파일정보를 불러온다.)

<?php
// loadpic.php
header("Content-Type: application/json");  //json을 사용하기 위해 필요한 구문

isset($_REQUEST["num"])  ? $num=$_REQUEST["num"] :   $num=''; 

require_once("../lib/mydb.php");
$pdo = db_connect();	

$now = date("Y-m-d");	     // 현재 날짜와 크거나 같으면 출고예정으로 구분
$nowtime = date("H:i:s");	 // 현재시간	

$myfile = fopen("temp.txt", "w") or die("Unable to open file!");
// $txt = "John Doe\n";
fwrite($myfile, $num);
fclose($myfile);

$sql=" select * from (본인의DB테이블명) where parentnum ='$num'";	

$recnum=0; 
$num_arr=array(); 
$parentnum_arr=array(); 
$img_arr=array(); 

 try{  
// 레코드 전체 sql 설정
   $stmh = $pdo->query($sql);            // 검색조건에 맞는글 stmh
   
   $i= 0;    
   while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {

            $num_arr[$i]        =$row["num"];			
			$parentnum_arr[$i] = $row["parentnum"];
			$img_arr[$i]       = $row["picname"];
			
			$i++;
        }		 
   } catch (PDOException $Exception) {
    print "오류: ".$Exception->getMessage();
}  

$recnum = $i;

//각각의 정보를 하나의 배열 변수에 넣어준다.
$data = array(
	"recnum"=>           $recnum,
	"num_arr" =>         $num_arr,
	"parentnum_arr" =>    $parentnum_arr,
	"img_arr" =>         $img_arr,

);   
//json 출력
echo(json_encode($data, JSON_UNESCAPED_UNICODE));

?>

 

view.php에서 초기 로드시 picname을 불러와서 배열에 담아줍니다.

// 사진파일 불러오기
$sql=" select * from (본인의DB테이블명) where parentnum ='$num'";
$picNum=0; 
$picData=array(); 

 try{  
// 레코드 전체 sql 설정
   $stmh = $pdo->query($sql);            // 검색조건에 맞는글 stmh   
   $i= 0;    
   while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
			$picData[$i]       = $row["picname"];			
			$i++;
        }		 
   } catch (PDOException $Exception) {
    print "오류: ".$Exception->getMessage();
}  
$picNum=$i;

이제 거의 다 왔습니다. 실제 화면을 실행해 보고 결과를 보여드리겠습니다.

사진이 잘 등록되었습니다.

위의 삭제버튼을 누르면 서버에서 삭제되고, 화면에서도 삭제됩니다.

삭제되는 소스코드는 자바스크립트(제이쿼리) 구문을 확인하시면 됩니다.

파일등록 생각보다 코드가 길고, 복잡하지만, 한번 해 두면 두고두고 쓸 수 있는 것 같습니다.

 

 

 

 

반응형
댓글