0

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);
  • 3
    This has nothing to do with SQL or PDO specifically, it's about variable scope. P.S. As a design pattern, you should usually try to avoid globals. – ADyson Feb 15 '21 at 13:42
  • `By 'not working' it completely stops the php script`...it should also produce an error too. Make sure you have error reporting on in PHP, so you can see specific messages to help you diagnose issues. – ADyson Feb 15 '21 at 13:43
  • Add [error reporting](http://stackoverflow.com/questions/845021/) to the top of your file(s) _while testing_ right after your opening PHP tag for example. Even if you are developing on a server configured as LIVE you will now see any errors. ` – RiggsFolly Feb 15 '21 at 13:59
  • thanks guys, error reporting is the answer I needed :) – Sammy123 Feb 15 '21 at 14:13

0 Answers0