Page 1 of 1

Function Problem

Posted: Sat Jan 30, 2010 8:24 pm
by carleihar
I'm using this function (included in a config include) to validate a login on every page.

Code: Select all

<?php
 
include('mysqli_connect.php');
 
function validate_login($un, $pass) {
 
        if ($result = mysqli_query($dbc, "SELECT COUNT(*) FROM users WHERE username='" . $un . "' AND pass=SHA1('$pass')")) {  
    
        $row = mysqli_fetch_assoc($result);  
          
            if ($row['COUNT(*)'] == 1) { 
                
                $validate = TRUE;
                
            } else { 
                
                $validate = NULL;
            
            }
        }
            return $validate;
}
?>
And using this code to call it.

Code: Select all

<?php
require_once('includes/mysqli_connect.php');
include('includes/config.inc.php');
 
if(!validate_login($_COOKIE['username'], $_COOKIE['password'])) {  
  echo 'Sorry, you\'re not logged in. Go <a href="login.php">here</a>';
  mysqli_close($dbc);
  exit();  
} else {
 
    echo 'Welcome!';
    }
 
?>
I'm getting this error:

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/content/e/q/u/equianadmin/html/includes/config.inc.php on line 7
Sorry, you're not logged in. Go here

Any help?

Re: Function Problem

Posted: Sat Jan 30, 2010 8:33 pm
by AlanG
On line 6 of the config file, add this:

Code: Select all

global $dbc;
Variables within functions exist within their own scope. You will need to specify that you are using a variable declared in the global scope.

You could also reference it directly from the globals array:

Code: Select all

if ($result = mysqli_query($GLOBALS['dbc'], "SELECT COUNT(*) FROM users WHERE username='" . $un . "' AND pass=SHA1('$pass')")) {
If you want more information on this, you can go to: http://php.net/manual/en/language.variables.scope.php

Re: Function Problem

Posted: Sat Jan 30, 2010 8:48 pm
by carleihar
Ahh that make sense. Thanks so much!

Unfortunately it's still saying that I'm not logged in. Any help on that?

Re: Function Problem

Posted: Sat Jan 30, 2010 9:10 pm
by SimpleManWeb
Are you sure that your connect file is successfully connecting you to your database? Check there, because I don't see any other problems with the code that you posted.

Hope this helps

Re: Function Problem

Posted: Sat Jan 30, 2010 9:19 pm
by stuartshields
This might be a long shot, are you declaring your function properly? Also I would check to see if your connection to your DB is correct.

Re: Function Problem

Posted: Sat Jan 30, 2010 9:30 pm
by carleihar
I know my connection is working. I have the code above that calls the function, so you can see if I called it correctly ;)

Re: Function Problem

Posted: Sat Jan 30, 2010 9:52 pm
by stuartshields
Are the cookies being called when the function is being called?

Re: Function Problem

Posted: Sun Jan 31, 2010 9:23 am
by carleihar
I got it working now. Thanks everyone! :)