我正在尝试使用OOP方法将给定here的代码转换为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;
}
}
Firebug抛出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;
我哪里出错?
答案 0 :(得分: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[]
计数器,因为这会将每个带有数字键的新行附加到数组上。
答案 1 :(得分: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"]);
}
答案 2 :(得分: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++) {