2016-06-03 4 views
0

블로그에서 작업 중이며이를 파악할 수 없습니다. 이 경우 ($result->fetchColumn())이 작동해야합니다. 그것은 오류를 제공하지만 데이터 (행)가 존재하면 아무것도 표시하지 않습니다. 뭐가 잘못 되었 니?PHP PDO가 데이터가 제대로 작동하지 않는지 확인하십시오.

<?php 
     $id = $_GET["id"]; 
     $sql = "SELECT * FROM `posts` WHERE `id` = $id"; 
     $result = $conn->query($sql); 
     if ($result->fetchColumn() > 0) { 
     while($row = $result->fetch(PDO::FETCH_ASSOC)) { 
      echo '<div class="post-preview"> 
        <a> 
         <h2 class="post-title"> 
          '.$row["title"].' 
         </h2> 
         <h3 class="post-subtitle"> 
          '.$row["content"].' 
         </h3> 
        </a> 
        <p class="post-meta"><a href="#">'.$row["creator"].'</a> | '.$row["date"].'</p> 
       </div> 
       <hr>'; 
      } 
     } 
     else { 
      echo "<center><h1>Post does not exist.</h1></center>"; 
      header("Refresh: 2; url=index.php"); 
     } 
    ?> 

줄을 제거 할 때마다 if ($result->fetchColumn() > 0) {이 정상적으로 작동합니다. 하지만 $ id가 데이터베이스에 있는지 확인해야합니다. 그렇다면 데이터를 보여 주어야하며 그렇지 않다면 오류를 표시하고 index.php에 다시 링크해야합니다.

+1

'if ($ result-> fetchColumn()> 0)'이해야 할 일은 무엇입니까? 행을 가져 와서 계속 가져올 수 있는지 확인하십시오. 또한,'fetchColumn'이 무엇을하는지 그리고 어디서 사용되어야 하는지를 PHP 매뉴얼을 참고하여 보았습니까? – Mjh

+0

코드가 SQL 삽입에 취약합니다! 이 쿼리를 실행하려면 [PDO 준비된 문구] (https://phpdelusions.net/pdo#prepared)를 사용하십시오! –

답변

1

코드는

그냥 변수 당신의 $ 행을 채우고는 아무것도 포함 여부 참조 훨씬 간단 할 수있다.

<?php 
$stmt = $conn->prepare("SELECT * FROM `posts` WHERE `id` = ?"); 
$stmt->execute([$_GET["id"]]); // essential to protect from SQL injection! 
$row = $stmt->fetch(PDO::FETCH_ASSOC) 
if ($row) { 
     echo '<div class="post-preview"> 
       <a> 
        <h2 class="post-title"> 
         '.$row["title"].' 
        </h2> 
        <h3 class="post-subtitle"> 
         '.$row["content"].' 
        </h3> 
       </a> 
       <p class="post-meta"><a href="#">'.$row["creator"].'</a> | '.$row["date"].'</p> 
      </div> 
      <hr>'; 
    } 
    else { 
     echo "<center><h1>Post does not exist.</h1></center>"; 
     header("Refresh: 2; url=index.php"); 
    } 
관련 문제