0

I'm having some trouble with executing code after I call a function. When I execute this code, it connects to the server fine in the try function, "PreEchoTest" is displayed but when CheckUsername(); is called, no echo functions come after that, not even the echoes inside of the CheckUsername() function.

The SQL Query is correct as I've tried Querying it directly to the SQL server. I'm not being displayed errors when I load the code, but I'm wondering why nothing is echoing when the function CheckUsername(); happens. I'm thinking maybe there is an error in there and that's stopping execution? Anyone know?

    try 
    {
        $conn = new PDO({Server Details Are Here});
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "PreEchoTest";
        CheckUsername();
        echo "AfterEchoTest";
    }
    catch (PDOException $e) 
    {
        print("Error connecting to Server.");
        die(print_r($e));
    }



function CheckUsername()
{
$sql = "SELECT Username FROM Students UNION SELECT Username FROM Parents";
$result = $conn->query($sql);

    //Show data for each row.
    while ($row = $result->fetch(PDO::FETCH_ASSOC))
    {
        if ($username == $row['Username'])
        {
            echo "Success";
            //CheckUserPassword($row['Username']);
        }
        else 
        {
            echo "Fail";
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Lewis
  • 566
  • 4
  • 21
  • 2
    `$result = $conn->query($sql);` `$conn` is not defined within the scope of that function. – Patrick Q May 08 '18 at 19:44
  • I've tried removing the Start function as well but it's still the same issue, I've updated the code now where the try catch is outside of a function, but the same issue still occurs. I'm fairly new to PHP, I assume functions work similarly to C# functions where variables outside of a function can still be accessed within a function, check the updated code. – Lewis May 08 '18 at 19:50
  • "variables outside of a function can still be accessed within a function". Nope. See the marked duplicate. – Patrick Q May 08 '18 at 19:51
  • @Lewis the answer is still valid - you need to learn variable scopes. – Alex May 08 '18 at 19:51
  • Ahh alright thanks you two! I'll take a look now and see if I can get it working. – Lewis May 08 '18 at 20:21

0 Answers0