PDO prepared SELECT statement isn't working

我只是一个虾纸丫 提交于 2019-12-13 05:15:34

问题


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:


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


来源:https://stackoverflow.com/questions/18647416/pdo-prepared-select-statement-isnt-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!