Search code examples
phpmysqlselectif-statement

How to check whether a mysql select statement result has a value or not in php?


I have a textbox UserName and a Check Availability button next to it..... I have checked the availability by passing UserName textbox value..... But it doesn't seem to work....

Here is what i am doing?

echo $UserName = $_GET['CheckUsername'];
$_SESSION['state'] = $State;
$queryres = "SELECT dUser_name FROM tbl_login WHERE dUser_name='$UserName'";
$result = mysql_query($queryres,$cn) or die("Selection Query Failed !!!");

if($result==true) // this condition doesn't seem to work
    {
       echo "User Name Available";
    }
else
{
        echo "Sorry user name taken";
}

Solution

  • Please make sure you're escaping your inputs for MySQL. Passing data directly from $_GET, $_POST or any of the other superglobals is unsafe.

    // Escape any quote characters in the input
    $UserName = mysql_real_escape_string($_GET['CheckUsername'], $cn);
    $_SESSION['state'] = $State;
    
    $queryres = "SELECT dUser_name FROM tbl_login WHERE dUser_name='$UserName' LIMIT 1";
    $result = mysql_query($queryres, $cn) or die("Selection Query Failed !!!");
    
    if (mysql_num_rows($result) > 0) {
        echo 'User name exists in the table.';
    } else {
        echo 'User name does not exist in the table.';
    }