RE: [PHP] counting records in db

From: Date: Thu, 26 Oct 2006 18:30:37 +0000
Subject: RE: [PHP] counting records in db
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-243700@lists.php.net to get a copy of this message
> Would it be ok to use the same code to check if customer is loged in? > > $query = mysql_query(" > SELECT COUNT(Username) as NoOfRecords > FROM customers > WHERE Username = '$Username' AND Password = > '$Password'"); > if (mysql_result($query, 0) == 0) > { > echo 'Please try again'; > } > else > { > header('location: index.php); > exit; > } Assuming that the 'Username' field is unique, then the COUNT() is not necessary in this case as the number of returned results would never be greater than 1. A more reasonable approach would be something like this: <? $query = "SELECT UserID, Password FROM customers WHERE Username = '{$_POST['username']}'"; $result = mysql_query($query); if(mysql_num_rows($result) == 1) { if($_POST['password'] == mysql_result($result, 0, 'Password')) { $_SESSION['logged_in'] = 'Yes'; $_SESSION['user_id'] = mysql_result($result, 0, 'UserID'); header('location: index.php); }else{ echo "Invalid Password!"; } }else{ echo "Invalid Username!"; } ?>

« previous php.general (#243700) next »