What I want to do: Use functions to connect to my database with PDO so i don't have to type the connection out every time.
What I tried:
library.php:
function dbconpdo() {
$db = new PDO('mysql:host=localhost;dbname=dbname', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
test.php:
include_once "templates/library.php";
try {
dbconpdo();
$stmt = $db->query('SELECT * FROM users');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['user'];
echo $row['password'];
echo "test";
}
} catch(PDOException $ex) {
echo $ex;
}
That didn't work, It didn't give me any errors but didn't output anything at all.
What worked:
test.php:
try {
$db = new PDO('mysql:host=localhost;dbname=dbname', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $db->query('SELECT * FROM users');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['user'];
echo $row['password'];
echo "test";
}
} catch(PDOException $ex) {
echo $ex;
}
It worked, but the problem with that is that i had to remove the function altogether and type it(the connection) out manually.
My question: How do I use functions(or anything similar) to make a PDO connection to my database so that I don't have to manually type it out each time I want to connect?