如何从旧查询 PHP 到使用 PDO PHP 准备好的语句查询

How to from Old Query PHP to Query with Prepared Statements with PDO PHP

我正在使用 PDO 将我的旧代码(在很多方面都很有用)带到新标准。 问题是,我没有收到 return,没有错误消息,什么也没有。 我的代码执行以下操作:对数据库进行查询,如果有任何结果($resultado),它会在数组中创建数据顺序。 可以请有人帮我吗? 我尝试了 Array 方法和 Object 方法,没有甜甜圈 :/

旧代码:

$sql_code =
   "SELECT news_id, news_title, news_date, news_resume
   FROM news
   WHERE news_show = 'S'
   ORDER BY news_date DESC
   ";

   $result = mysql_query($sql_code);

   if ($result) {
    $rows = mysql_num_rows($result);
      for ($i=0; $i<$rows; $i++) {
      $aID[]     = mysql_result($result, $i, "news_id");
      $aTitle[]  = mysql_result($result, $i, "news_title");
      $aDate[]   = mysql_result($result, $i, "news_date");
      $aResume[] = mysql_result($result, $i, "news_resume");
      }
   }
?>

无效的新代码:

try
      {
            $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpasswd);
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $stmt = $dbh->prepare("SELECT   news_id, news_title, news_date, news_resume
                                   FROM     news
                                   WHERE    news_show = :newsS
                                   ORDER BY news_date DESC");

            $stmt->execute(array('newsS' => 'S'));

            while ($sql_code = $stmt->fetchall(PDO::FETCH_ASSOC))
            {
                $result = mysql_query($sql_code);
            }

        }
        catch(PDOException $e)
        {
            echo "Error:". $e->getMessage();
        }

   $result = mysql_query($sql_code);

   if ($result)
   {
    $rows = mysql_num_rows($result);
      for ($i=0; $i<$rows; $i++)
      {
      $aID[]     = mysql_result($result, $i, "news_id");
      $aTitle[]  = mysql_result($result, $i, "news_title");
      $aDate[]   = mysql_result($result, $i, "news_date");
      $aResume[] = mysql_result($result, $i, "news_resume");
      }
   }
?>

如果您使用 PDO,则不要调用任何 mysql_XXX 函数,您必须对所有内容使用 PDO 方法。

$stmt->fetchAll() returns 结果的所有行。要处理它,只需使用 foreach 循环。

try
{
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpasswd);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $dbh->prepare("SELECT   news_id, news_title, news_date, news_resume
                           FROM     news
                           WHERE    news_show = :newsS
                           ORDER BY news_date DESC");

    $stmt->execute(array('newsS' => 'S'));
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($result as $row) {
        $aId[] = $row['news_id'];
        $aTitle[] = $row['news_title'];
        $aDate[] = $row['news_date'];
        $aResume[] = $row['news_resume'];
    }
}
catch(PDOException $e)
{
    echo "Error:". $e->getMessage();
}