如何在PHP中将SQL查询与基本身份验证连接起来

时间:2017-05-13 06:16:09

标签: php mysql rest api authentication

我想将我的基本授权与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'");

1 个答案:

答案 0 :(得分:0)

  

警告mysql_query,mysql_fetch_array,mysql_connect等..扩展在PHP 5.5.0中已弃用,并且已在PHP 7.0.0中删除。   相反,应该使用MySQLi或PDO_MySQL扩展。

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

        }