I have a function which uses:
require_once("connect.php");
function get_username($uid){
$stmt = $pdo->prepare("SELECT username FROM users WHERE uid= ?");
try {
$stmt->execute(array($uid));
} catch (PDOException $e) {
echo $e -> getMessage(); exit;
}
$row = $stmt->fetch();
return($row['username']);
}
$id = 1;
echo get_username($id);
But it says :
Call to a member function prepare() on a non-object
I’m a bit confused on what this means i have wrong, i’m wondering if its because I am using it in a function ?
EDIT:
My Connect script¬
$dsn = 'mysql:dbname=test_db;host=127.0.0.1';
$user = 'test_user';
$password = 'test_pass';
try {
$pdo = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
error_reporting(E_ALL);
session_start();
Yes, it’s because you’re using it in a function.
$pdois in the global scope, and is not in the scope of the function.You either need to access the
$pdoglobal by referencing it in the function as a global variable:Or pass
$pdoin when you call the function