【问题标题】:PHP MySQLi to PDO?PHP MySQLi 到 PDO?
【发布时间】:2017-09-03 16:34:05
【问题描述】:

我不知道为什么我的代码没有返回true,while 循环工作正常,但是有一个问题。

$PDO_result = $db_PDO->prepare("SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE '?%' ");
$PDO_result->bindParam(1, $pismenka[$i]);
$PDO_result->execute();

在这里,当我 var_dump() $PDO_result 我在数组中得到一项时,下面的 while 循环应该可以工作:

while($row = $PDO_result->fetch(PDO::FETCH_ASSOC))

但事实并非如此。

工作 MySQLi:

$result = mysqli_query($connect_to_db, "SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE '$pismenka[$i]%' ");

while($row = mysqli_fetch_array($result))

【问题讨论】:

  • not duplicate % cant be in Param ....,我还有其他问题,然后他

标签: php mysql mysqli pdo


【解决方案1】:

最简单的解决方案是将$pdo->fetch(PDO::FETCH_ASSOC) 更改为$pdo->fetchAll(PDO::FETCH_ASSOC)

fetchAll 返回请求查询中的所有行,而fetch 仅获取 1 行(第一行)

例子:

<?php


try {

    $PDO_result = $db_PDO->prepare("SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE ?");

    //Execute by inserting an array:
    if (!$PDO_result->execute([$pismenka[$i] . "%" ])) { //Added ."%" 
        die('Error!');
    }

    //Fetch rows:
    $rows = $PDO_result->fetchAll(PDO::FETCH_ASSOC);

    //Go trough each row:
    foreach ($rows as $row) {
        //Do something
    }

    //Catch exceptions thrown by PDO
} catch (PDOException $ex) {
    print_r($ex);
}

【讨论】:

  • fetch 应该返回第 1 行,然后是第 2 行,然后是第 3 行.....如 PHP.net 中所述吗?
  • 我不是 100% 确定这一点,但是看看这个答案,它让我想起了你的问题:stackoverflow.com/questions/19488364/… 但是fetchAll 你不必在总而言之,您只需将所有内容都放在一个关联数组中,但 IMO 它做同样的工作,fetchAll在您实际做的事情的上下文中更清晰
  • 尝试将您的代码放入try{ code here } catch(PDOException $ex){ print_r($ex); }
  • 应该是 execute([ $pismenka[$i] . "%" ]),因为 % 在原始查询中。
  • @tadman 是正确的,在我和 OP 进行 Skype 会话以找出问题之后,我忘记更新答案了。会更新:)
猜你喜欢
  • 2015-06-17
  • 2017-12-06
  • 1970-01-01
  • 2012-02-22
  • 2023-04-02
  • 2013-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多