【问题标题】:My select statement with PDO its not working correctly我的 PDO 选择语句无法正常工作
【发布时间】:2014-04-09 18:53:23
【问题描述】:

在这里,我将登录会话存储在我的 $userId 变量中以获取我的 ID:

$ userId = $_SESSION['result']['id'];

如果用户想要搜索某个名称,我在这里存储一个 $_SESSION['where']:

 if(isset($_POST['sendFiltro'])){
            $search = $_POST['search'];
            if(!empty($search) && $search != 'Name:'){
                $_SESSION['where'] = "AND name LIKE '%$search%'";
                header('Location: index2.php?exe=adminis/admins');
            }else{
                unset($_SESSION['where']);
                header('Location: index2.php?exe=adminis/adminis');
            }
        }

在这里,我执行我的选择语句,让我的管理员显示在表格中:

$pag = (empty($_GET['pag']) ? '1' : $_GET['pag']);
$max = 10;
$first = ($pag * $max) - $first;
$where = isset($_SESSION['where']) ? $_SESSION['where'] : '';
$readAdmin = $pdo->prepare("SELECT * from admins WHERE id != :id {$where} ORDER BY name ASC, level ASC LIMIT :first, :max");
$readAdmin->bindParam(':id', $userId, PDO::PARAM_INT);
$readAdmin->bindParam(':first', $first, PDO::PARAM_INT);
$readAdmin->bindParam(':max', $max, PDO::PARAM_INT);  
$readAdmin->execute();
$readAdminRows = $readAdmin->rowCount();
 if(!$readAdminRows)
    {
       echo 'There are no recors in admins table';
    }
    else
   {
    //I show my table
    }

我的 Admins 表中有 20 个记录,它总是说我的 admin 表中没有记录。

您是否在我的代码中看到了导致这种情况发生的一些错误?

如果我从我的 sql 语句 WHERE id != :id 中删除它,它可以工作,但我不想在表中显示当前管理员的会话。

【问题讨论】:

  • 为什么是 {$where} 而不是“.$where”。 ?
  • 您应该为所有内容使用占位符,而不仅仅是某些内容。 $where 在这里完全没有转义。您是否真的允许从会话中任意注入 SQL?
  • @MrJack 这就是PHP string interpolation 的工作原理。为什么这么多人不知道?
  • 感谢您的意见,但我不知道其他方法可以做到这一点!
  • @tadman 我们中的一些人在 PHP 之前就学会了编写其他语言;)

标签: php mysql sql pdo


【解决方案1】:
$readAdminRows = $readAdmin->rowCount();

如果您将 PDO 配置为使用无缓冲查询,则 rowCount() 函数始终返回 0:

$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

我建议您尝试获取结果集的第一行,如果第一次获取仍然没有返回任何内容,那么您没有匹配项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    相关资源
    最近更新 更多