TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Absolute Beginners (http://www.talkphp.com/absolute-beginners/)
-   -   Checking empty field then connect (http://www.talkphp.com/absolute-beginners/3707-checking-empty-field-then-connect.html)

9three 12-03-2008 06:34 PM

Checking empty field then connect
 
I'm having issues figuring out what the problem is. I have a log in form that checks to see if the fields are empty, if they are, then it throws an error out. If they put something in both fields, it checks to see if they are a valid in the database.

PHP Code:

function db_connect() {
    
$dbconn = @mysql_connect('localhost''username''password') or die('Unable to connect to database at this time, please try again later.');
    
$select = @mysql_select_db('dbname') or die('Unable to select database, please try again later.');
}

function 
login($username$password){
    
$error = array();
    if (
count($_POST) > 0) { // assume the form has been submitted
    
if (empty($_POST['username']) || empty($_POST['password'])) $error[] = 'A valid username and password is needed';
        if (
count($errors)) {
    echo 
"$errors";
    }
    
    }else { 
//Check username and password
    
$conn db_connect();
    
$result $conn->query("SELECT * FROM admin WHERE username='$username' AND password=sha1('$password')");
    if (!
$result){
        die(
'Unable to connect to database at this time, please try again later.');
    }
    }


Whats happening is that my script is automatically trying to connect to my database when I load the page. I want it to run when the user hits "login".

In my HTML I have
Code:

<?php
login('username', 'password')
?>

What could I possibly be doing wrong ?

trmbne2000 02-06-2009 10:15 PM

The problem with your code is the if (count($errors)) { on line 4 of the login function. Your error array is $error earlier in the code.

I see that you are passing in the username and password arguments, yet you are still looking for the POST values in the function. It may be better to use:
Code:

function login($username, $password){
    $error = array();
    if (empty($username) || empty($password)) {
        echo 'A valid username and password is needed';
    } else {
        $conn = db_connect();
        $result = $conn->query("SELECT * FROM admin WHERE username='$username' AND password=sha1('$password')");
        if (!$result){
            die('Unable to connect to database at this time, please try again later.');
        }
    }
}

AND
Code:

  if (isset($_POST['username'])) {
    login($_POST['username'],$_POST['password']);
  }

Not sure if you only gave a partial example of your db_connect() method, but you may need to look at that as well (no reference to the db object is returned, so you may not be able to query it).

--Andrew


All times are GMT. The time now is 03:11 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0