dpsu84620 2017-01-18 21:34
浏览 67
已采纳

使用Prepared语句将MySQL SELECT结果存储在php变量中

I am trying to user prepared statements to find a user record and store the users ID in a php variable to use later on. I would like to echo the variable contents. How do I check the result using Prepared statements?

My CODE:

 if ((isset($_POST['overrideUsername'])) and (isset($_POST['overridePassword'])) and (isset($_POST['overrideUniqueID']))) {



    $overridePasswordInput = $_POST['overridePassword'];
    $overrideUsernameInput = $_POST['overrideUsername'];
    $roleID = '154';
    $overrideUniqueID = $_POST['overrideUniqueID'];

    //Not sure how to properly compare stored passwords vs password given by user...
    $overridePassword = mysqli_real_escape_string($overridePasswordInput);
    $overrideUsername = mysqli_real_escape_string($overrideUsernameInput);





    //connect  to the database 
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if(mysqli_connect_errno() ) {
        printf('Could not connect: ' . mysqli_connect_error());
        exit();
    }

    $conn->select_db($dbname);

    if(! $conn->select_db($dbname) ) {
        echo 'Could not select database. '.'<BR>';
    }


$sql1 = "SELECT users.id FROM users WHERE (users.login = ?) AND (users.password = ?)";

    $stmt1 = $conn->prepare($sql1);
    $stmt1->bind_param('ss', $overrideUsername, $overridePassword);
    $stmt1->execute();
    $stmt1->bind_result($userID);     
    $stmt1->get_result();


    if ($stmt1->get_result()) {

        echo $userID;

    } else {

      echo 'User credentials incorrect. Please try again';

    }

 $stmt1->close();


 //Close the Database connection.
 $conn->close();

 }//End If statement

Further more, this is the pre-existing code the original programmer used to authenticate users into the program:

if(!defined("noStartup")){
$scriptname = basename($_SERVER["PHP_SELF"]);
$phpbmsSession = new phpbmsSession;

//Testing for API login
if(strpos($scriptname,"api_")!==false){
    if(isset($_POST["phpbmsusername"]) && isset($_POST["phpbmspassword"])){
        $phpbmsSession->loadDBSettings();

        include_once("include/db.php");
        $db = new db();
        $phpbmsSession->db = $db;

        include_once("common_functions.php");           
        $phpbmsSession->loadSettings($sqlEncoding);
        $phpbms = new phpbms($db);


        if(!$phpbmsSession->verifyAPILogin($_POST["phpbmsusername"],$_POST["phpbmspassword"],ENCRYPTION_SEED))
            $error = new appError(-700,"","Login credentials incorrect",true,true,true,"json");
    } else
        $error= new appError(-710,"","No login credentials passed",true,true,true,"json");
} else {

    $phpbmsSession->loadDBSettings($sqlEncoding);


    include_once("include/db.php");
    $db = new db();

    $phpbmsSession->db = $db;

    $phpbmsSession->loadSettings($sqlEncoding);

    include_once("common_functions.php");
    $phpbms = new phpbms($db);

    if(!isset($noSession))
        $phpbmsSession->startSession();

      if (!isset($_SESSION["userinfo"]) && $scriptname != "index.php") {

        if(isset($loginNoKick)){
            if(!isset($loginNoDisplayError))
                exit();
        } else{
            goURL(APP_PATH."index.php");
        }
      }

   }

  $db->stopOnError=true;
}//end if

And the verifying function:

function verifyAPIlogin($user,$pass){
    $thereturn=false;
    $this->db->stopOnError = false;

    $querystatement = "SELECT id, firstname, lastname, email, phone, department, employeenumber, admin, usertype
                    FROM users 
                    WHERE login!=\"Scheduler\" AND login=\"".mysql_real_escape_string($user)."\" 
                    AND password=ENCODE(\"".mysql_real_escape_string($pass)."\",\"".mysql_real_escape_string(ENCRYPTION_SEED)."\") 
                    AND revoked=0 AND portalaccess=1";
    $queryresult = $this->db->query($querystatement);
    if(!$queryresult) {
        $error = new appError(-720,"","Error retrieving user record",true,true,true,"json");
        return false;
    }

    if($this->db->numRows($queryresult)){
        //We found a record that matches in the database
        // populate the session and go in
        $_SESSION["userinfo"]=$this->db->fetchArray($queryresult);

        $querystatement="UPDATE users SET modifieddate=modifieddate, lastlogin=Now() WHERE id = ".$_SESSION["userinfo"]["id"];
        $queryresult=@ $this->db->query($querystatement);
        if(!$queryresult) {
            $error = new appError(-730,"","Error Updating User Login Time",true,true,true,"json");
        } else
            $thereturn=true;
    }
    return $thereturn;  
  }

}//end loginSession class

NOTE: I have already tested that my $_POST() values are successfully coming through to my script.

EDIT:: added more code to give a better overall picture of what I'm attempting to do. Any shared tuturials on password encryption/authenticating users would be greatly appreciated.

Thank you!

  • 写回答

1条回答 默认 最新

  • doudou5023 2017-01-20 01:05
    关注

    As I mentioned in the comment, PHP now has a couple built in methods to handle encryption and decryption of passwords that you might find helps solve your problem:

    password_hash and password_verify

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 java代码写在记事本上后在cmd上运行时无报错但又没生成文件
  • ¥15 关于#python#的问题:在跑ldsc数据整理的时候一直抱这种错误,要么--out识别不了参数,要么--merge-alleles识别不了参数(操作系统-linux)
  • ¥15 PPOCRLabel
  • ¥15 混合键合键合机对准标识
  • ¥100 现在不懂的是如何将当前的相机中的照片,作为纹理贴图,映射到扫描出的模型上
  • ¥15 魔霸ROG7 pro,win11.息屏后会显示黑屏,如图,如何解决?(关键词-重新启动)
  • ¥15 有没有人知道这是哪里出了问题啊?要怎么改呀?
  • ¥200 C++表格文件处理-悬赏
  • ¥15 Windows Server2016本地登录失败
  • ¥15 复合卡卡号轨道写入芯片卡