Please note that this example is vulnerable to injection and uses plain-stored passwords...
(PHP 5, PHP 7, PHP 8)
mysqli::real_query -- mysqli_real_query — 执行一个mysql查询
面向对象风格
过程化风格
对数据库执行单条查询,其结果可以使用 mysqli_store_result() 或 mysqli_use_result() 检索或存储。
If the query contains any variable input then parameterized prepared statements should be used instead. Alternatively, the data must be properly formatted and all strings must be escaped using the mysqli_real_escape_string() function.
为了确定给定的查询是否应返回结果集,参阅 mysqli_field_count()。
成功时返回 true
, 或者在失败时返回 false
。
If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR
) and the requested operation fails,
a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT
,
a mysqli_sql_exception is thrown instead.
Please note that this example is vulnerable to injection and uses plain-stored passwords...
Well, we don't know if $password is in plain text because it was never defined in the example.
New passwords should be stored using
<?php
$crypt_pass = password_hash($password, PASSWORD_DEFAULT);
?>
Where PASSWORD_DEFAULT = BCRYPT algorithm
Then to compare a user entered password to a database stored password, we use:
<?php
$valid = password_verify($password, $crypt_pass);
?>
Which returns true or false.
As for being vulnerable to injection, this is true. To avoid this, use sprintf() or vsprintf() to format the query and inject the values using mysqli::real_escape_string, like so:
<?php
$vals = [$db->real_escape_string($username), $db->real_escape_string($password)];
$query = vsprintf("Select * From users Where username='%s' And password='%s'", $vals);
$result = $db->real_query($query);
?>
Straightforward function - simply connect to the database and execute a query, similar to this function bellow.
<?php
function check_password($username, $password) {
// Create connection
$db = new mysqli('localhost','database_user','database_pass','database_name');
// Check for errors
if($db->connect_errno){
echo $db->connect_error;
}
// Execute query
$result = $db->real_query("Select * From users Where username='$username' And password='$password'");
// Always check for errors
if($db->connect_errno){
echo $db->connect_error;
}
return $result == true;
}
?>
Very easy.
Replace database_user, database_pass and database_name with the proper names, and the text inside real_query with your actual query.
Don't forget the quotes on either side (except for numbers, there you can omit them) otherwise it won't work. Hope that helps someone.