开发者

Matching strings in PhP/MySQL

T开发者_如何学Pythonhe 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);


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';


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);
}


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜