PDO准备的SELECT语句不起作用 [英] PDO prepared SELECT statement isn't working

查看:78
本文介绍了PDO准备的SELECT语句不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难使用PDO准备好的语句从表中检索数据,

i'm having a hard time trying to retrieve data from a table using PDO prepared statements,

下面是我的代码不起作用,$ post始终为空.

Below is my code which isn't working, $post is always empty.

    //connection to db has been made
    $stmt = $db->prepare("SELECT * FROM posts WHERE id = ?");
    $stmt->bindValue(1,$_GET['id']);
    $post = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->execute();

我非常有信心问题会出现在第三行中,所以请让我知道是否还有另一种获取数据的方法,而不是fetchAll(PDO :: FETCH_ASSOC).

I'm quite confident the problem occurs in the third line, so please let me know if there is another way to get the data rather than fetchAll(PDO::FETCH_ASSOC).

非常感谢.

推荐答案

您实际上并没有执行该方法,但否则,您的代码看起来还不错!

You're not actually executing the method, but otherwise, your code looks fine!

// Assuming $_GET['id'] has a value (thanks Mike!)
$stmt = $db->prepare("SELECT * FROM posts WHERE id = ?");
$stmt->bindValue(1, $_GET['id']);
$stmt->execute();

$post = $stmt->fetchAll(PDO::FETCH_ASSOC);

顺便说一句,我还要确保$_GET['id']是有效的; is_int($_GET['id'])返回可以提供帮助的布尔值.

As an aside, I'd also make sure that $_GET['id'] is valid; is_int($_GET['id']) returns a boolean that could help.

获取帖子后,请确保对其进行迭代.

After fetching your posts, make sure to iterate through them.

if($post != null && count($post) > 0) {
    for($i = 0; $i < count($post); $i++) {
        echo $post[$i]['title'] . '<br />';
    }
}

这篇关于PDO准备的SELECT语句不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆