PDO prepared SELECT statement isn't working

2019-08-26 06:58发布

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

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();

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).

Thanks alot.

1条回答
Rolldiameter
2楼-- · 2019-08-26 07:16

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);

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 />';
    }
}
查看更多
登录 后发表回答