PDO JSON编码多个HTML表行

时间:2013-03-24 00:48:55

标签: php json pdo

我正在构建一个PHP函数,该函数应该响应jQuery Ajax调用,具体取决于提交的id。可以有多个具有相同ID的表单,我无法弄清楚为什么它不会发送回多个记录。 PS:如果我在星期一之前没有弄明白,我父亲会杀了我......

我的PHP:

<?php
  if (!empty($_GET['id'])) {
    $id = $_GET['id'];
    try {
      $objDb = new PDO('mysql:host=localhost;dbname=blankett', 'root', 'root');
      $objDb->exec('SET CHARACTER SET utf8');
      $sql = "SELECT * 
              FROM `forms`
              WHERE `id` = '$id'";
      $statement = $objDb->prepare($sql);
      $list = $statement->fetchAll(PDO::FETCH_ASSOC);
      if (!empty($list)) {
        $out = array();
        foreach ($list as $row ) {
          $out[] = '<tr><td><a href="'.$row['link_form'].'">'.$row['name_form'].'</a></td> <td>'.$row['date_added'].'</td></tr>';
        }
        echo json_encode(array('error' => false, 'list' => $out));
      } else {
        echo json_encode(array('error' => true));
      }
    } catch(PDOException $e) {
      echo json_encode(array('error' => true));
    }
  } else {
    echo json_encode(array('error' => true));
  }
?>

1 个答案:

答案 0 :(得分:1)

您正在错误地使用预准备语句。首先,您不应该将您的变量放在语句中。其次,您需要执行语句。

以下是php.net网站的一个例子:

$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();

以下是你将如何做到这一点:

$sql = "SELECT * 
FROM `forms`
WHERE `id` = :formID";

$statement = $objDb->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$statement ->execute(array(':formID' => $id));
$list= $statement ->fetchAll();