简体   繁体   中英

PDO prepared SELECT statement isn't working

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.

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 />';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM