how to check if a user exists in db with PHP

charmingduck
charmingduck used Ask the Experts™
on
The db has a row named first_name, and it has 11 users in it. I have this form that you can input a name and check if the name already exists in the db. How do I do that?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
try like this,

<?php
mysql_connect(HOST, USERNAME, PASSWORD);
mysql_select_db(DB_NAME);

if($_POST) {
    $name = mysql_real_escape_string($_POST['fname'];

    // check if name exists in db
    $sql = "SELECT first_name FROM persons WHERE first_name ='". $name."'";
	
    $query = mysql_query($sql) or die (mysql_error());
	
	// to check name
    if(mysql_num_rows($query) > 0) {
        // user exists
    } else {
        // user does not exist
    }
}

?>

Open in new window

Most Valuable Expert 2011
Top Expert 2016
Commented:
Please read this article.  From this question and some of your others, I am guessing that the design patterns shown here will be helpful to your current projects.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial