Converting mysql code to PDO gives no output
I am trying to convert the code given here to PDO using OOP approach. This is what I've got so far:
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开发者_如何学Python("name" => $row["name"], "comment" => $row["comment"], "date" => $row["date"]);
}
$response = $_GET["jsoncallback"] . "(" . json_encode($comments) . ")";
echo $response;
return TRUE;
}
catch(Exception $ex)
{
return FALSE;
}
}
Firebug throws the undefined variable: comments
error.
This is the original code:
$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;
Where have I gone wrong?
You are using $x < $row
when I think you intend to use $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++)
This whole loop could be better written this way:
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$comments[] = array("name" => $row["name"], "comment" => $row["comment"], "date" => $row["date"]);
}
There's no need for the $x
counter if you use the $comments[]
syntax, since that will append each new row with a numeric key onto the array.
Your for loop is wrong. You need to get the number of rows, then call $query->fetch()
on every loop iteration:
$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"]);
}
The following line has a syntax error (comma instead of semicolon):
for ($x = 0, $row = $query->fetch(PDO::FETCH_ASSOC); $x < $row; $x++) {
It should be:
for ($x = 0; $row = $query->fetch(PDO::FETCH_ASSOC); $x < $row; $x++) {
精彩评论