2017-12-31 45 views
0

나는 이것이 매우 일반적인 질문이라는 것을 알고 있지만, 내 코드에 무엇이 잘못되었는지 확인하는 데 도움을 찾고 있습니다. 관리자가 양식의 사진으로 새로운 야영장을 만들 수 있도록 내 데이터베이스를 만들려고합니다. 내 웹 사이트가 제대로 작동하고있는 것처럼 보입니다. 테스트 할 때 값이 채워지지 않고 필요한 값이 채워지지 않았 으면 성공 메시지가 표시되지만 내 데이터베이스로 정보가 전달되지 않습니다. 어떤 도움을 주시면 감사하겠습니다!sql이 데이터베이스에 삽입되지 않음

또한 매우 나쁜 코더로 사과드립니다.

관련 웹 사이트 코드 :

<section id="SIGNUP" style="text-align: center;" class="main-container"> 
     <div class="container" style="width:100%;"> 
     <h2 style="text-align:center; font-size:50px;">Add a New Campsite</h2> 
     <form id="newsletter" <form class="signup-form" action="includes/fetch.inc.php" method="POST" enctype="multipart/form-data" style="padding-top:50px; padding-bottom:50px; border-bottom:#e8491d 3px solid; border-top:#e8491d 3px solid;"> 
     <input type="integer" name="length" style="padding:4px; height:5%; width:25%; text-align:center; font-size:30px;" placeholder="Site Length"><br> 
      <input type="integer" name="width" style="padding:4px; height:5%; width:25%; text-align:center; font-size:30px;" placeholder="Site Width"><br> 
      <label for="fire">Fire Pit: </label><input type="checkbox" name="fire" value="No"> 
      <label for="electric">Electricity: </label><input type="checkbox" name="electric" value="No"> 
      <label for="sewer">Sewage: </label><input type="checkbox" name="sewer" value="No"></br> 
     <input type="decimal" name="price" style="padding:4px; height:5%; width:25%; text-align:center; font-size:30px;" placeholder="Price"><br> 
    <input type="file" id="upload_file" name="upload_file[]" onchange="preview_image();" multiple/> 
    <input type="submit" name="submit_image" value="Upload Image"/> 
</form> 
<div id="image_preview"></div> 
</div> 
</section>; 

fetch.inc.php/SQL 코드 : 모든 코드를 보지 않고 말할 하드

<?php 
if(isset($_POST['submit_image'])) { 

    require_once("dbh.inc.php"); 

    $length = mysqli_real_escape_string($conn, $_POST['length']); 
    $width = mysqli_real_escape_string($conn, $_POST['width']); 
    $price = mysqli_real_escape_string($conn, $_POST['price']); 
    //Error Handlers 
    //Check for empty fields 

    if (empty($length) || empty($width) || empty($price)) { 
     header("Location: ../admin.php?null-value"); 
     exit(); 
    } else { 

//insert image address into images folder and add the address to reservations table 
    for($i=0;$i<count($_FILES["upload_file"]["name"]);$i++) 
    { 
    $uploadfile=$_FILES["upload_file"]["tmp_name"][$i]; 
    $folder="images/"; 
    move_uploaded_file($_FILES["upload_file"]["tmp_name"][$i], "$folder".$_FILES["upload_file"]["name"][$i]); 
    $image = "$folder".$_FILES["upload_file"]["name"]; 


    $sql = "INSERT INTO campsites (length, width, fire, sewer, electric, price) 
    VALUES ('$length', '$width', '$fire', '$sewer', '$electric', '$price');"; 
    mysqli_query($conn, $sql); 
    header("Location: ../admin.php?signup=Success"); 
    exit(); 

// Transform checkbox values into binary sql values 

     if (isset($_POST['fire']) && ($_POST['fire'] == "value")) { 
      $fire .= "1"; 
     } else { 
      $fire .= "0"; 
     } 

    if (isset($_POST['sewer']) && ($_POST['sewer'] == "value")) { 
     $sewer .= "1"; 
    } else { 
     $sewer .= "0"; 
    } 

    if (isset($_POST['electric']) && ($_POST['electric'] == "value")) { 
     $electric .= "1"; 
    } else { 
     $electric .= "0"; 
    } 
    } 
} 

} 
exit(); 
?> 
+0

_ 수정 "을하지만 내 데이터베이스에 정보를 전달하지 않습니다"_, 당신은 그렇다면? 데이터베이스에 삽입 선에 도달 할 것으로 확신합니다 , 어떤 경고 메시지가 나옵니까? – andrewnagyeb

+0

두 가지 메시지 만 있습니다. 1 : 필요한 값이 없을 때 "위치 : ../admin.php?null-value"헤더가 나타납니다. 2 : 필요한 값이 있으면 Location을 얻을 수 있습니다. ./admin.php?signup=Success "헤더 실제 fetch.ini.php 페이지는 아무 것도 반환하지 않습니다. – tlhopbow

+0

'fire','sewer' 및'electric' 필드의 값은 기본적으로'No''이므로 어떻게 가치가 같습니까? – RamRaider

답변

3

당신이 정수로 변경하여 fire, sewerelectric의 필드 값을 편집하는 경우 1 (기본값)의 기본값을 사용하면 PHP에서 일부 논리를 단순화 할 수 있습니다.

insert 문은 실제로 SQL 삽입을 피하기 위해 prepared statements을 사용해야합니다.

또한 여기에있는 인라인 스타일보다 모양을 제어하기 위해 css을 사용하는 것이 좋습니다. 그러면 코드를 더 가볍고 읽기 쉬워지며 더 쉽게 변경할 수 있습니다!

아래의 코드는 모두 한 페이지에 있습니다. 원래 HTML 페이지와 PHP 코드를 두 구성 페이지로 나눌 필요가 있습니다. 이것으로 지금부터 일할 수 있어야합니다.아마도 그것은 관심이있을 수 있습니다 -

<?php 

    if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['length'], $_POST['width'], $_POST['price'])){ 
     try{ 

      require_once("dbh.inc.php"); 

      function uploaderror($code){ 
       switch($code) { 
        case UPLOAD_ERR_INI_SIZE: return "The uploaded file exceeds the upload_max_filesize directive in php.ini"; 
        case UPLOAD_ERR_FORM_SIZE: return "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; 
        case UPLOAD_ERR_PARTIAL: return "The uploaded file was only partially uploaded"; 
        case UPLOAD_ERR_NO_FILE: return "No file was uploaded"; 
        case UPLOAD_ERR_NO_TMP_DIR: return "Missing a temporary folder"; 
        case UPLOAD_ERR_CANT_WRITE: return "Failed to write file to disk"; 
        case UPLOAD_ERR_EXTENSION: return "File upload stopped by extension"; 
        default: return "Unknown upload error"; 
       } 
      } 

      $filefield='upload_file'; 
      $status=false; 
      $sql = "insert into `campsites` (`length`, `width`, `fire`, `sewer`, `electric`, `price`) values (?,?,?,?,?,?);"; 

      $length=filter_input(INPUT_POST,'length',FILTER_SANITIZE_NUMBER_INT); 
      $width=filter_input(INPUT_POST,'width',FILTER_SANITIZE_NUMBER_INT); 
      $price=filter_input(INPUT_POST,'price',FILTER_SANITIZE_NUMBER_INT); 

      $fire=isset($_POST['fire']) ? filter_input(INPUT_POST,'fire',FILTER_SANITIZE_NUMBER_INT) : 0; 
      $sewer=isset($_POST['sewer']) ? filter_input(INPUT_POST,'sewer',FILTER_SANITIZE_NUMBER_INT) : 0; 
      $electric=isset($_POST['electric']) ? filter_input(INPUT_POST,'electric',FILTER_SANITIZE_NUMBER_INT) : 0; 





      if(!$length or !$width or !$price){ 
       exit(header("Location: ../admin.php?null-value")); 
      } 

      $stmt=$conn->prepare($sql); 
      if(!$stmt) throw new Exception('Failed to prepare sql statement'); 

      $stmt->bind_param('iiiiii', $length, $width, $fire, $sewer, $electric, $price); 

      if(isset($_FILES[ $filefield ])){ 
       foreach($_FILES[ $filefield ]['name'] as $i => $name) { 
        if(!empty($_FILES[ $filefield ]['tmp_name'][$i])) { 

         $name = $_FILES[ $filefield ]['name'][$i]; 
         $size = $_FILES[ $filefield ]['size'][$i]; 
         $type = $_FILES[ $filefield ]['type'][$i]; 
         $tmp = $_FILES[ $filefield ]['tmp_name'][$i]; 
         $err = $_FILES[ $filefield ]['error'][$i]; 

         $target="images/{$name}"; 
         #$target='c:/temp/fileuploads/1/'.$name; 

         if(is_uploaded_file($tmp)){ 
          $bytes = move_uploaded_file($tmp, $target); 
         } else { 
          throw new Exception(sprintf('Error: %s',uploaderror($err))); 
         } 
        } 
       } 
      } 
      $result = $stmt->execute(); 
      $stmt->close(); 
      $conn->close(); 

      exit(header("Location: ../admin.php?signup=$result")); 

     }catch(Exception $e){ 
      echo $e->getMessage(); 
     } 
    } 

?> 

<!doctype html> 
<html> 
    <head> 
     <meta charset='utf-8' /> 
     <title></title> 
    </head> 
    <body> 
     <section id="SIGNUP" class="main-container"> 
      <div class="container"> 
       <h2>Add a New Campsite</h2> 

       <form class="signup-form" method="POST" enctype="multipart/form-data"> 

        <input type="number" name="length" placeholder="Site Length"><br> 
        <input type="number" name="width" placeholder="Site Width"><br> 

        <label for="fire">Fire Pit: </label><input type="checkbox" name="fire" value=1> 
        <label for="electric">Electricity: </label><input type="checkbox" name="electric" value=1> 
        <label for="sewer">Sewage: </label><input type="checkbox" name="sewer" value=1></br> 

        <input type="number" name="price" placeholder="Price"><br> 
        <input type="file" id="upload_file" name="upload_file[]" onchange="preview_image();" multiple/> 

        <input type="submit" name="submit_image" value="Upload Images & Save"/> 
       </form> 
       <div id="image_preview"></div> 
      </div> 
     </section> 
    </body> 
</html> 

는 내가 이미지에 대한 참조를 저장에 대한 마지막 코멘트가 데이터베이스에 저장되는 것을 만든 후 약 연극의 비트를했다.

의심 할 여지없이 실제 데이터베이스 스키마는 훨씬 복잡하지만 데모 용 테이블을 2 개 빠르게 만들었습니다.

create table `campsites` (
    `id` int(10) unsigned not null auto_increment, 
    `length` smallint(5) unsigned not null default '0', 
    `width` smallint(5) unsigned not null default '0', 
    `fire` bit(1) not null default b'0', 
    `sewer` bit(1) not null default b'0', 
    `electric` bit(1) not null default b'0', 
    `price` decimal(10,0) unsigned not null default '0', 
    primary key (`id`) 
) 
collate='utf8_general_ci' 
engine=innodb; 

create table `campsite_images` (
    `id` int(10) unsigned not null auto_increment, 
    `cid` int(10) unsigned not null default '0', 
    `photo` varchar(128) not null default '0', 
    primary key (`id`), 
    index `cid` (`cid`), 
    constraint `fk_cs_img` foreign key (`cid`) references `campsites` (`id`) on update cascade on delete cascade 
) 
collate='utf8_general_ci' 
engine=innodb; 



mysql> describe campsites; 
+----------+------------------------+------+-----+---------+----------------+ 
| Field | Type     | Null | Key | Default | Extra   | 
+----------+------------------------+------+-----+---------+----------------+ 
| id  | int(10) unsigned  | NO | PRI | NULL | auto_increment | 
| length | smallint(5) unsigned | NO |  | 0  |    | 
| width | smallint(5) unsigned | NO |  | 0  |    | 
| fire  | bit(1)     | NO |  | b'0' |    | 
| sewer | bit(1)     | NO |  | b'0' |    | 
| electric | bit(1)     | NO |  | b'0' |    | 
| price | decimal(10,0) unsigned | NO |  | 0  |    | 
+----------+------------------------+------+-----+---------+----------------+ 


mysql> describe campsite_images; 
+-------+------------------+------+-----+---------+----------------+ 
| Field | Type    | Null | Key | Default | Extra   | 
+-------+------------------+------+-----+---------+----------------+ 
| id | int(10) unsigned | NO | PRI | NULL | auto_increment | 
| cid | int(10) unsigned | NO | MUL | 0  |    | 
| photo | varchar(128)  | NO |  | 0  |    | 
+-------+------------------+------+-----+---------+----------------+ 

그리고 위의 코드

<?php 

    if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['length'], $_POST['width'], $_POST['price'])){ 
     try{ 
      $redirect=false; 
      $message=false; 
      $filefield='upload_file'; 
      $status=false; 
      $imgdir='c:/temp/fileuploads/1/'; 
      $results=array(); 

      #require_once("dbh.inc.php"); 

      $dbhost = 'localhost'; 
      $dbuser = 'root'; 
      $dbpwd = 'xxx'; 
      $dbname = 'xxx'; 
      $conn = new mysqli($dbhost, $dbuser, $dbpwd, $dbname); 




      function uploaderror($code){ 
       switch($code) { 
        case UPLOAD_ERR_INI_SIZE: return "The uploaded file exceeds the upload_max_filesize directive in php.ini"; 
        case UPLOAD_ERR_FORM_SIZE: return "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; 
        case UPLOAD_ERR_PARTIAL: return "The uploaded file was only partially uploaded"; 
        case UPLOAD_ERR_NO_FILE: return "No file was uploaded"; 
        case UPLOAD_ERR_NO_TMP_DIR: return "Missing a temporary folder"; 
        case UPLOAD_ERR_CANT_WRITE: return "Failed to write file to disk"; 
        case UPLOAD_ERR_EXTENSION: return "File upload stopped by extension"; 
        default: return "Unknown upload error"; 
       } 
      } 



      $sql = "insert into `campsites` (`length`, `width`, `fire`, `sewer`, `electric`, `price`) values (?,?,?,?,?,?);"; 
      $sql_image = 'insert into `campsite_images` (`cid`,`photo`) values (?,?)'; 

      $length=filter_var(filter_input(INPUT_POST,'length',FILTER_SANITIZE_NUMBER_INT), FILTER_VALIDATE_FLOAT); 
      $width=filter_var(filter_input(INPUT_POST,'width',FILTER_SANITIZE_NUMBER_INT), FILTER_VALIDATE_FLOAT); 
      $price=filter_var(filter_input(INPUT_POST,'price',FILTER_SANITIZE_NUMBER_INT), FILTER_VALIDATE_FLOAT); 

      $fire=isset($_POST['fire']) ? filter_input(INPUT_POST,'fire',FILTER_SANITIZE_NUMBER_INT) : 0; 
      $sewer=isset($_POST['sewer']) ? filter_input(INPUT_POST,'sewer',FILTER_SANITIZE_NUMBER_INT) : 0; 
      $electric=isset($_POST['electric']) ? filter_input(INPUT_POST,'electric',FILTER_SANITIZE_NUMBER_INT) : 0; 





      if(!$length or !$width or !$price){ 
       if($redirect) exit(header("Location: ../admin.php?null-value")); 
      } 
      if(!is_numeric($length) or !is_numeric($width) or !is_numeric($price)){ 
       throw new Exception('Non-Float values for length, width and price are not allowed.'); 
      } 

      $stmt=$conn->prepare($sql); 
      if(!$stmt) throw new Exception('Failed to prepare sql statement'); 
      $stmt->bind_param('iiiiii', $length, $width, $fire, $sewer, $electric, $price); 


      $stmt_image=$conn->prepare($sql_image); 
      if(!$stmt_image)throw new Exception('Unable to prepare image sql statement'); 
      $stmt_image->bind_param('is', $id, $target); 


      /* insert record for campsite */ 
      $results[]=$stmt->execute(); 

      /* Get the ID for the campsite that was just added */ 
      $id=$stmt->insert_id; 

      /* Process any & all images that are uploaded */ 
      if(isset($_FILES[ $filefield ])){ 
       foreach($_FILES[ $filefield ]['name'] as $i => $name) { 
        if(!empty($_FILES[ $filefield ]['tmp_name'][$i])) { 

         $name = $_FILES[ $filefield ]['name'][$i]; 
         $size = $_FILES[ $filefield ]['size'][$i]; 
         $type = $_FILES[ $filefield ]['type'][$i]; 
         $tmp = $_FILES[ $filefield ]['tmp_name'][$i]; 
         $err = $_FILES[ $filefield ]['error'][$i]; 

         $target = $imgdir . $name; 

         if(is_uploaded_file($tmp)){ 
          $bytes = move_uploaded_file($tmp, $target); 
          $results[]=$stmt_image->execute(); 
         } else { 
          throw new Exception(sprintf('Error: %s', uploaderror($err))); 
         } 
        } 
       } 
       $stmt_image->close(); 
      } 

      $result=new stdClass; 
      $result->failed=0; 
      $result->success=0; 

      array_walk($results, function($value){ 
       global $result; 
       if($value==0)$result->failed++; 
       if($value==1)$result->success++; 
      }); 

      $message=sprintf('Record(s) added - Failed:%d, Success:%d', $result->failed, $result->success); 

      $stmt->close(); 
      $conn->close(); 



      if($redirect) exit(header("Location: ../admin.php?signup=true")); 

     }catch(Exception $e){ 
      $message=$e->getMessage(); 
     } 
    } 

?> 

<!doctype html> 
<html> 
    <head> 
     <meta charset='utf-8' /> 
     <title>Campsite booking form</title> 
     <style> 
      html,html *{ 
       font-family:calibri,verdana,arial; 
       box-sizing:border-box; 
      } 
      #signup{ 
       text-align: center; 
       width:50%; 
       float:none; 
       margin:0 auto; 
      } 
      h2{text-align:center; font-size:4rem;} 
      h3{font-size:0.95rem;color:green;} 
      input{padding:1rem;} 

      input[type='text'], 
      input[type='number']{ 
       float:none; 
       width:calc(33% - 1rem); 
       margin:0.5rem auto; 
      } 
      fieldset{ 
       width:90%; 
       border:none; 
       margin:1rem auto; 
       float:none; 
      } 
      input[type='file']{ 
       width: 0.1px; 
       height: 0.1px; 
       opacity: 0; 
       overflow: hidden; 
       position: absolute; 
       z-index: -1; 
      } 
      input[type='file'] + label{ 
       font-weight: 700; 
       color: black; 
       background-color: #E5E4E2; 
       display: inline-block; 
       border:1px solid black; 
       padding:0.25rem; 
       width:90%; 
       cursor:pointer; 
       float:none; 
       margin:0 auto; 
      } 


      label[for='upload_file']:hover { 
       background: rgba(240,182,198,0.75)!important; 
      } 

      input[type='submit']{ 
       width:90%; 
       float:none; 
       margin:1rem auto; 
      } 
      #services label{ 
       padding:1rem; 
       display:inline-block; 
       clear:none; 
       float:none; 
       margin:0 auto; 
       width:calc(33% - 5px);!important; 
      } 
      ul#list{font-size:0.7rem;} 
      #image_preview img{margin:0.25rem;padding:0.25rem;outline:1px dotted gray;} 
     </style> 
     <script> 
      /* self-executing anonymous function */ 
      (function(){ 

       var getaspect=function(w,h){ 
        w=parseFloat(w); 
        h=parseFloat(h); 
        if(w==h)return 1; 
        else if(w > h) return 2; 
        else if(h > w) return 3; 
        else return 4; 
       } 
       var getratio=function(w,h){ 
        return parseFloat(w)/parseFloat(h); 
       } 
       var roundNumber=function(i,p){ 
        return Math.floor(i * Math.pow(10, p))/Math.pow(10, p); 
       }; 
       var getfilesize=function(i){ 
        var kb=1024; 
        var mb=Math.pow(kb,2); 
        var gb=Math.pow(kb,3); 
        var tb=Math.pow(kb,4); 

        if(i > 0 && i < kb) return i+'bytes'; 
        else if(i >= kb && i < mb) return roundNumber(Math.abs(i/kb),2) + 'Kb'; 
        else if(i >= mb && i < gb) return roundNumber(Math.abs(i/mb),2) + 'Mb'; 
        else if(i >= gb && i < tb) return roundNumber(Math.abs(i/gb),2) + 'Gb'; 
        else if(i >= tb) return roundNumber(Math.abs(i/tb),2) + 'Tb'; 
       }; 

       var size=150; 
       var options={ 
        capture:false, 
        once:false, 
        passive:true 
       }; 
       document.addEventListener('DOMContentLoaded',function(e){ 

        var oImages=[]; 
        var oInput=document.getElementById('upload_file'); 
        var oPreview=document.getElementById('image_preview'); 
        var oList=document.getElementById('list'); 

        oInput.addEventListener('change',function(event){ 
         var files=this.files; 
         for(var i=0; i < files.length; i++){ 
          var file=files.item(i); 
          var obj={ 
           'file':file, 
           'name':file.name, 
           'size':file.size, 
           'lastModified':file.lastModified, 
           'lastModifiedDate':file.lastModifiedDate, 
           'type':file.type 
          }; 
          oImages.push(obj); 

          var li=document.createElement('li'); 
           li.dataset.name=obj.name; 
           li.dataset.lastmod=obj.lastModifiedDate; 
           li.dataset.type=obj.type; 
           li.innerHTML=obj.name + ' [ '+getfilesize(obj.size)+' ]'; 

          oList.appendChild(li); 

          /********************/ 
          /* Show a preview */ 
          var img = document.createElement('img'); 
           img.file=obj.file; 
           img.dataset.name=obj.name; 
           img.title=obj.name; 
           img.onload=function(event){ 

            var ratio=getratio(this.width,this.height); 
            switch(getaspect(this.width, this.height)){ 
             case 1: 
              this.width=size; 
              this.height=size; 
             break; 
             case 2: 
              this.width=size; 
              this.height=size/ratio; 
             break; 
             case 3: 
              this.height=size; 
              this.width=size * ratio; 
             break; 
             case 4: 
              alert('error') 
             break; 
            } 
            window.URL.revokeObjectURL(this.src); 
           }; 

          /* add new thumbnail to the DOM */ 
          oPreview.appendChild(img); 

          /* read the file and set the image source */ 
          var reader = new FileReader(); 
           reader.onload = (function(a) { return function(e) { a.src = e.target.result; }; })(img); 
           reader.readAsDataURL(obj.file); 

         } 
        }.bind(oInput),options); 
       },options); 
      })(); 
     </script> 
    </head> 
    <body> 
     <section id='signup' class='main-container'> 
      <div class='container'> 
       <h2>Add a New Campsite</h2> 
       <?php 
        if($message){ 
         echo "<h3>$message</h3>"; 
        } 
       ?> 
       <form class='signup-form' method='POST' enctype='multipart/form-data'> 

        <fieldset id='dimensions'> 
         <input type='number' name='length' placeholder='Site Length' step=1 min=1 max=1000 /> 
         <input type='number' name='width' placeholder='Site Width' step=1 min=1 max=1000 /> 
         <input type='number' name='price' placeholder='Price' step='0.5' min=0 max=1000 /> 
        </fieldset> 

        <fieldset id='services'> 
         <label for='fire'>Fire Pit: <input type='checkbox' name='fire' value=1></label> 
         <label for='electric'>Electricity: <input type='checkbox' name='electric' value=1></label> 
         <label for='sewer'>Sewage: <input type='checkbox' name='sewer' value=1></label> 
        </fieldset> 

        <fieldset id='files'> 
         <input type='file' id='upload_file' name='upload_file[]' multiple/> 
         <label for='upload_file' title='Optional: Upload photos'> 
          <svg xmlns='http://www.w3.org/2000/svg' width='20' height='17' viewBox='0 0 20 17'> 
           <path d='M10 0l-5.2 4.9h3.3v5.1h3.8v-5.1h3.3l-5.2-4.9zm9.3 11.5l-3.2-2.1h-2l3.4 2.6h-3.5c-.1 0-.2.1-.2.1l-.8 2.3h-6l-.8-2.2c-.1-.1-.1-.2-.2-.2h-3.6l3.4-2.6h-2l-3.2 2.1c-.4.3-.7 1-.6 1.5l.6 3.1c.1.5.7.9 1.2.9h16.3c.6 0 1.1-.4 1.3-.9l.6-3.1c.1-.5-.2-1.2-.7-1.5z'></path> 
          </svg> <span>Choose a file…</span> 
         </label> 
        </fieldset> 

        <fieldset id='bttns'> 
         <input type='submit' name='submit_image' value='Upload Images & Save'/> 
        </fieldset> 

       </form> 
       <div id='image_preview'></div> 
       <ul id='list'></ul> 
      </div> 
     </section> 
    </body> 
</html> 
+0

왜 작동하지 않는지에 관해서 일하고 내게 똑같은 맥락이 없지만, 당신이 내게 주신 것을 진심으로 감사드립니다. 필자가 쓴 것보다 훨씬 더 기능적 일 것 같아요. 또한 베스트 프랙티스를 활용하지 않는다는 것에 전적으로 동의합니다. 또한 모범 사례에 대해 전혀 알지 못한다고 말하며, 약간의 지침으로 내 깊이에서 벗어난 프로젝트에 몰두했습니다. 반 기능적이라면 기쁠 것입니다. – tlhopbow

+0

어디에서 실패할까요? 이미지가 업로드됩니까? 실패한 SQL입니까? – RamRaider

+0

죄송합니다. 나는 그 의견이 조금시기 상조입니다. 나는 당신의 충고에 따라 bool 대신 int로 sql 값을 변경 한 다음 제공 한 두 코드 세트를 모두 삽입했습니다. 내가 그것을 밖으로 정렬하려고하지만 작고 뭔가 확신 해요,하지만 "스토리지 오류가 발생했습니다 : 예상치 못한 구문 오류") ','또는 ']'in/storage/ssd2/948/4122948 /public_html/includes/fetch.inc.php on line 28 "--- 괄호로 괄호 안의 불일치를 변경하려고 시도했지만"구문 분석 오류 : 구문 오류, 예기치 않은 오류 ", '예상', '또는'오류가 발생했습니다. ' – tlhopbow

1

(예를 들어, 어떤 당신의 require_once("dbh.inc.php");가하고있는)하지만 난 ' PHP 및/또는 MySQL에 의해 오류가 발생할 것으로 추측됩니다.

이 제대로 실행 된 더 강력한 조금 쿼리를 확인하기 위해 검사를 추가하는 코드를 만들려면 :
mysqli_query($conn, $sql); 
if (!mysqli_query($conn, $sql)) { 
    error_log("SQL query error: " . mysqli_error($conn)); 
} 

이 그런 다음 PHP 오류 로그를 확인, 당신이 거기에 결과를 볼 수 있습니다.

php.inimysql.cnf 파일을 검사하여 오류 로그 파일을 찾을 수 있습니다. 당신이 리눅스를 사용하는 경우 공통 기본 위치 :

/var/log/php_errors.log 
/var/log/mysqld.log 

당신의 cPanel 같은 것을 실행하는 호스팅 제공 업체를 사용하는 경우, 당신은 거기에 로그 파일에 대한 액세스를 찾아야한다.

당신 디버깅을 쉽게 만드는 화면하는 오류를 인쇄 할 수 있지만 보안상의 이유로 생산 코드에서 권장 하지입니다. 당신이 당신의 오류 로그에 접근이 마음에 일단 어쨌든이 작업을 수행 할 필요가 있지만, 안되는 레코드 :

mysqli_query($conn, $sql); 
if (!mysqli_query($conn, $sql)) { 
    print "Error: " . mysqli_error($conn); 
    error_log("SQL query error: " . mysqli_error($conn)); 
} 
+0

나는 그것이 가장 명확하지는 않지만 (oops), dbh.inc.php는 데이터베이스에 대한 나의 연결이다. 아마 내가 아는이 코드의 엉망진창에있는 유일한 것은 올바르게 작동 할 것입니다! – tlhopbow

+0

또한, 000webhostapp을 사용하고 있으며 내 로그를 조사하는 방법을 모릅니다. 바라기를 나는 ewbsite에 그것을 발견 할 수있다! https://campease.000webhostapp.com/index.php – tlhopbow

+0

000webhost.com처럼 보입니다. cPanel을 사용하십시오. 웹 사이트는 귀하의 웹 사이트를 제어하고 관리하기 위해 로그인하는 웹 사이트입니다. ** Metrics ** 섹션이 있어야합니다. 여기에 ** Errors ** 섹션이 표시되어야하며 여기에 오류 로그가 표시됩니다. (또는 단순히'print "오류로 화면에 오류를 표시하십시오 :". mysqli_error ($ conn);'위의 제안, 그러나 디버깅을 마친 후에 꺼내십시오. :)) – Jonathan