Captain Lightning
Captain Lightning

Reputation: 10773

Matching strings in PhP/MySQL

The var $username needs to check for a match. How can I do this?

Progress:

if (isset($_GET["username"]) && !empty($_GET["username"])) 
{
    $username = $_GET['username'];

    $usercheck = mysql_query("SELECT * FROM wp_users WHERE user_login=".$username."",$con);
    closeCursor($usercheck);

Upvotes: 0

Views: 161

Answers (3)

Ives.me
Ives.me

Reputation: 2394

Hey I recommend using sprintf for security reasons.

$query = sprintf("SELECT * FROM friends WHERE user='%s' AND password='%s'",
    mysql_real_escape_string($_GET['username']),
    mysql_real_escape_string($_GET['password']);

// Perform Query
$result = mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

Upvotes: 1

Lee
Lee

Reputation: 13542

mysql_num_rows() would tell you whether any users matched the provided username. You should also use mysql_real_escape_string to ensure that your username value is safely escaped for use in the query. Also -- be sure your strings are quotes (using single-quotes) inside the mysql query.

Something like this should get you pointed in the right direction:

$username = mysql_real_escape_string($_GET['username'], $con);

$usercheck = mysql_query("SELECT * FROM wp_users WHERE user_login='".$username."'",$con);
if( mysql_num_rows($usercheck) <= 0 ) {
   // error: no such user was found
} else {
   // found one or more matching users
}

Upvotes: 0

shamittomar
shamittomar

Reputation: 46702

Do it like this:

1) Escape the variable to prevent SQL injection using mysql_real_escape_string.
2) Use quotes around the variable in where clause, because it is a string.
3) Check whether more than 0 rows were returned or not using mysql_num_rows.

 $username = mysql_real_escape_string($_GET['username']);
 $usercheck = mysql_query("SELECT * FROM wp_users WHERE user_login='".$username."'",$con);

 if(mysql_num_rows($usercheck)>0)
      echo 'USER FOUND';
 else
      echo 'NOT FOUND';

Upvotes: 2

Related Questions