I am trying to run a query using database credentials from a config file but I keep getting the following error: Uncaught Error: Call to a member function prepare() on null
config.php file:
$host = 'xxxx';
$dbname = 'xxxx';
$username = 'xxxx';
$password = 'xxxx.';
try {
$conn = new PDO("mysql:host=$host; dbname=$dbname;", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "$e->getMessage()";
}
functions.php
session_start();
include 'config.php';
function getAddress(){
$output = "";
if (isset($_SESSION['userid'])){
$userid = $_SESSION['userid'];
try {
$stmt = $conn->prepare('SELECT address FROM users WHERE id = :userid');
$stmt->bindParam(':userid', $userid);
$stmt->execute();
$result = $stmt -> fetch();
if(empty($result)){
$output = "Your information cannot be retrieved";
} else {
$output = $result['address'];
}
} catch (PDOException $e) {
$output = $e->getMessage();
}
$conn = null;
} else {
$output = "An error has occured, please try again";
}
return $output;
}
index.php (html page)
<?php
session_start();
include 'functions.php';
?>
...
<p><?php echo getAddress();?></p>
...
So my index page runs a function (getAddress()
) from the functions.php script which connects to a db using credentials stored in config.php.