Reputation: 380
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/>";
}
?>
Upvotes: 2
Views: 82
Reputation:
$stmt->execute()
returns a boolean indicating success/failure.
Instead, use this:
$stmt->execute();
$result = $stmt->fetchAll();
Upvotes: 3