簡體   English   中英

使用PHP PDO很難從sql查詢中獲取數據

[英]Having an hard time fetching data from sql query using PHP PDO

我有一個腳本並連接到數據庫,然后將數據插入數據庫。 但是我在獲取數據時遇到問題。

這是我得到的錯誤消息:致命錯誤:在第24行的C:\\ xampp \\ htdocs \\ projects \\ forms \\ db.php中,對布爾值上的成員函數fetchAll()進行調用

我究竟做錯了什么?

這是腳本

<?php
    //This script provides connection to the database//
    //Connect
    $user="root";
    $pass="";
    try {
        $connection = new PDO('mysql:host=localhost;dbname=thetest', $user, $pass);
    } catch (Exception $e) {
        print "Error!: " . $e->getMessage() . "<br/>";
    die();
    }

    //Insert
    try {
        $stmt = $connection->prepare("INSERT INTO `users`(`name`, `lastname`, `age`) VALUES(?,?,?)");
        $stmt->execute(array("Dave", "Smithers", "22"));
    } catch (Exception $e) {
        echo "Error!: " . $e->getMessage() . "<br/>";
        die();
    }

    //Fetch
    try {
        $stmt = $connection->prepare("SELECT `name` FROM `users` WHERE `lastname` = 'Smithers'");
        $result = $stmt->execute();
        $user = $result->fetchAll();
        print_r($user);
    } catch (Exception $e) {
        echo "Error!: " . $e->getMessage() . "<br/>";
    }
?>  

$stmt->execute()返回一個布爾值,指示成功/失敗。

而是使用以下命令:

$stmt->execute();
$result = $stmt->fetchAll();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM