0

Hey i did a php code to login and sign-up for a project and there is an issue i still cant figure after searching.

So i have 2 errors :

Fatal error: Uncaught Error: Call to a member function query() on null in C:\wamp64\www\Projet2\bdd.php on line 17

Notice: Undefined variable: bdd in C:\wamp64\www\Projet2\bdd.php on line 17

That line 17 is :

15 - function comparer($login, $motDePasse) {
16 -    extract($GLOBALS);
17 -    $requete = $bdd->query('SELECT Login, motDePasse FROM utilisateur');
18 -    $fetch = $requete->fetch();

    if ($login == $fetch["login"] && $motDePasse == $fetch["motDePasse"])
    {return true;}

    $requete->closeCursor();
}

And this is the file where i call that function :

<?php
    session_start();
    function verifier()
    {
        include 'bdd.php';
        $bdd = new PDO("mysql:host=$ip;port=$port;dbname=$db;charset=utf8",$user,$password);
        comparer($_POST['id'], $_POST['password']);
    }

Honestly tought it was the fact i called the database outside the file but i used the same process here and it worked :

if (isset($_SESSION["id"]) && $_SESSION["id"] == "ajouter")
{
    include 'bdd.php';
    $bdd = new PDO("mysql:host=$ip;port=$port;dbname=$db;charset=utf8",$user,$password);
    ajouter($_POST['id'], $_POST['password'], $_POST['mail']);
}

With that :

function ajouter($login,$motDePasse, $email) {
    extract($GLOBALS);
    $requete = $bdd->prepare('INSERT INTO utilisateur(login, motDePasse, email) VALUES ( :login, :motDePasse, :email)');
    $requete->execute(array(
    'login' => $login,
    'motDePasse' => $motDePasse,
    'email' => $email
    ));
    $requete->closeCursor();
}
  • Where is `$GLOBALS` defined? – mardubbles Jun 05 '22 at 21:06
  • @mardubbles `$GLOBALS` is a [superglobal containing all global variables](https://www.php.net/manual/en/reserved.variables.globals.php). `extract($GLOBALS);` is a really really hideous line of code, though. – IMSoP Jun 05 '22 at 21:07
  • Ok I see @IMSoP. I looked up `extract()`. How would `$bdd` get included in this scope is what I was after, for the OP? Because it is used without any definition or reference, and so *would* be null. – mardubbles Jun 05 '22 at 21:09
  • Variable scope doesn't depend on what file you're in, it depends on what *function* you're in. See the linked duplicate. Rather than messing around with `$GLOBALS`, learn the value of having separate pieces of code with their own scope. – IMSoP Jun 05 '22 at 21:11
  • @mardubbles I'm presuming there's something relevant in 'bdd.php'; but absolutely, the problem is not understanding variable scope, which is why I've closed it against a reference. – IMSoP Jun 05 '22 at 21:12

0 Answers0