简体   繁体   English

在PhP / MySQL中匹配字符串

[英]Matching strings in PhP/MySQL

The var $username needs to check for a match. var $ username需要检查是否匹配。 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 . 1)使用mysql_real_escape_string转义变量以防止SQL注入。
2) Use quotes around the variable in where clause, because it is a string. 2)在where子句中的变量周围使用引号,因为它是一个字符串。
3) Check whether more than 0 rows were returned or not using mysql_num_rows . 3)使用mysql_num_rows检查是否返回了0行以上。

 $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. 出于安全原因,我建议使用sprintf。

$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. mysql_num_rows()会告诉您是否有任何用户匹配提供的用户名。 You should also use mysql_real_escape_string to ensure that your username value is safely escaped for use in the query. 您还应该使用mysql_real_escape_string来确保用户名值安全地转义以便在查询中使用。 Also -- be sure your strings are quotes (using single-quotes) inside the mysql query. 另外-确保您的字符串是mysql查询中的引号(使用单引号)。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM