I want to put sql queries in a function so I can use them easily, however I can't understand why it doesn't work if the PDO object is a global object. But if I declare the PDO every time the function is called, it only works once. Am I misunderstanding something very basic here? I'm very new to SQL. Thanks :)
PS. By 'not working' it completely stops the php script on the prepare statement.
//This Does work
function validate($checkEmail, $checkId)
{
//----------------------------
$pdo = new PDO("mysql:host=localhost;dbname=dbname", "name", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//----------------------------
$stmt = $pdo->prepare('SELECT id FROM members WHERE Email = :email');
$stmt->execute(['email' => $checkEmail]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
}
validate($email, $id);
//This Doesn't work
//----------------------------
$pdo = new PDO("mysql:host=localhost;dbname=dbname", "name", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//----------------------------
function validate($checkEmail, $checkId)
{
$stmt = $pdo->prepare('SELECT id FROM members WHERE Email = :email');
$stmt->execute(['email' => $checkEmail]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
}
validate($email, $id);