gpt4 book ai didi

php - 如何在 PHP 中连接 SQL 查询和基本身份验证

转载 作者:行者123 更新时间:2023-11-29 18:59:50 25 4
gpt4 key购买 nike

我想将我的基本授权与我的 MySQL 数据库连接。实际上,我正在用 PHP 开发一个登录 REST API。目前,我已在 PHP 授权脚本中硬编码了我的用户名和密码,但我想连接到 MySQL 并通过基本授权使用我的数据库验证用户名和密码。

这是我的代码:

<?php 
// User name and password for authentication

$username = 'admin';
$password = 'password';

if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) ||
($_SERVER['PHP_AUTH_USER'] != $username) || ($_SERVER['PHP_AUTH_PW'] != $password)) {
// The user name/password are incorrect so send the authentication headers
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Guitar Wars"');
exit('<h2>Guitar Wars</h2>Sorry, you must enter a valid user name and
password to access this page.');
}
?>

我想嵌入这样的查询:

$query = mysql_query("SELECT username FROM login WHERE username='$username' and password='$password'");

最佳答案

Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.

Mysqli 准备语句

1)首先连接数据库,并使用用户给定的用户名和密码查询数据库,最后根据行数可以知道用户是否有效。

        //db connection

$servername = "localhost"; //host name

$username = "username"; //username

$password = "password"; //password

$mysql_database = "dbname"; //database name

//mysqli prepared statement

$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());

mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");

$stmt = $conn->prepare("SELECT * FROM $tbl_name WHERE username=? and password=? ");

$stmt->bind_param('ss',$myusername,$mypassword);

The argument may be one of four types:

//i - integer
///d - double
//s - string
//b - BLOB
//change it by respectively

$stmt->execute();
$get_result =$stmt->get_result();

$row_count= $get_result->num_rows;

if($row_count>0)
{
echo "valid user ";
}
else
{
echo "not valid user";

}

关于php - 如何在 PHP 中连接 SQL 查询和基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43949879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com