2

I have a script and connects to a database, then inserts data into a database. However I am having an issue fetching the data.

Here is the error message I get: Fatal error: Call to a member function fetchAll() on boolean in C:\xampp\htdocs\projects\forms\db.php on line 24

What am I doing wrong?

Here is the script

<?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/>";
    }
?>  
1

1 Answer 1

3

$stmt->execute() returns a boolean indicating success/failure.

Instead, use this:

$stmt->execute();
$result = $stmt->fetchAll();
Sign up to request clarification or add additional context in comments.

3 Comments

Should have been a comment
Really I can't detect difference in your code with the code question .. What is that ?
@stack - The user believed $stmt->execute() returned a result set when it returns a boolean

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.