This is my code:
class DB {
static $instance;
function get() {
if (self::$instance === null) {
self::$instance = new PDO('mysql:host=localhost;dbname=forum', 'root', 'root');
}
return self::$instance;
}
function getAllUsers() {
$users = array();
$sql = "SELECT * FROM users";
foreach (self::get()->query($sql) as $row) {
$users[] = new User($row);
}
return $users;
}
}
And now I’m calling the getAllUsers function in here:
class App {
function showUsers() {
$users = DB::getAllUsers();
}
Except its giving me an error:
Warning: Invalid argument supplied for foreach()
When I’m doing var_dump on self::get im getting a bool(false)
Can someone tell me what I’m doing wrong?
PDO::query returns a PDOStatement object only if it is successful in sending the query to the database and getting back a valid response (i.e. there were no SQL errors returned by the driver). However, in the event that it fails it will return
false. So you must check for this in order to handle errors. Also, you can optionally put PDO into Exception Mode to have it throw an exception any time it encounters an error. That way you can use try/catch to handle errors whenever call on PDO objects. See the example below…With PDO’s default error mode (silent):
With PDO in Exception Mode: