2011-05-20 31 views
2

我試圖使用OOP方法將給定的代碼here轉換爲PDO。這是我到目前爲止有:將mysql代碼轉換爲PDO不會輸出

的comments.php:

public function loadComments() { 
       $sql = "SELECT * FROM `comments` 
         WHERE 
         `comments`.`ImageID` = :imageid ;"; 

      try 
      { 
       $imageid = $_REQUEST['imageid']; 



       $query = $this->_db->prepare($sql); 
       $params = array(':imageid' => $imageid); 
       $query->execute($params); 

       for ($x = 0, $row = $query->fetch(PDO::FETCH_ASSOC); $x < $row; $x++) { 
       $comments[$x] = array("name" => $row["name"], "comment" => $row["comment"], "date" => $row["date"]);  
        } 

       $response = $_GET["jsoncallback"] . "(" . json_encode($comments) . ")"; 
       echo $response; 
       return TRUE; 

      } 
      catch(Exception $ex) 
      { 
       return FALSE; 
      } 
    } 

螢火蟲拋出undefined variable: comments錯誤。

這是原來的代碼:

$query = mysql_query("SELECT 
          * FROM `comments` 
          WHERE 
          `comments`.`ImageID` = '$imageid' ;"); 

     //loop through and return results 
     for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) { 
      $row = mysql_fetch_assoc($query); 

      $comments[$x] = array("name" => $row["name"], "comment" => $row["comment"], "date" => $row["date"]);    
     } 

     //echo JSON to page 
     $response = $_GET["jsoncallback"] . "(" . json_encode($comments) . ")"; 
     echo $response; 

我在哪裏出了錯?

回答

2

您正在使用$x < $row當我想你打算使用$x < $numrows

for ($x = 0, $row = $query->fetch(PDO::FETCH_ASSOC); $x < $row; $x++) 
                  ^^^^^ 
$numrows = $query->rowCount(); 
for ($x = 0, $row = $query->fetch(PDO::FETCH_ASSOC); $x < $numrows; $x++) 

這整個循環,可以更好地這樣寫的:

while ($row = $query->fetch(PDO::FETCH_ASSOC)) { 
    $comments[] = array("name" => $row["name"], "comment" => $row["comment"], "date" => $row["date"]);  
} 

有沒有必要,因爲如果你使用$x計數器$comments[]語法,因爲它會將每個新行添加一個數字鍵到數組上。

+0

謝謝。那樣做了! – input 2011-05-20 20:04:16

0

你的for循環是錯誤的。你需要得到的行數,然後調用$query->fetch()在每次循環:

$numrows = //... 
for ($x = 0; $x < $numrows; $x++) { 
    $row = $query->fetch(PDO::FETCH_ASSOC); 
    $comments[$x] = array("name" => $row["name"], "comment" => $row["comment"], "date" => $row["date"]);  
} 
0

下面這行有語法錯誤(逗號而不是分號):

for ($x = 0, $row = $query->fetch(PDO::FETCH_ASSOC); $x < $row; $x++) { 

它應該是:

for ($x = 0; $row = $query->fetch(PDO::FETCH_ASSOC); $x < $row; $x++) { 
+0

該逗號語法實際上是有效的。 http://php.net/manual/en/control-structures.for.php – 2011-05-20 20:04:15