转移到mysqli

时间:2013-06-04 14:57:41

标签: php mysql mysqli

我已经决定转移到mysqli,因为当人们发现我的mysql代码时,我一直受到抨击: - )

有人可以验证下面的内容是否正确,一切正常但我只想确保在移动到网站的其他部分之前我没有做一些愚蠢或存在安全风险。 这是登录时用户名/密码检查的php。

<?php
//Start session
session_start();

//Include database connection details
require_once('db_connect.php');

//Array to store validation errors
$errmsg_arr = array();

//Validation error flag
$errflag = false;


// cleanup POST variables
$username = mysqli_real_escape_string($mysqli, stripslashes(trim($_POST['username'])));
$password = mysqli_real_escape_string($mysqli, stripslashes(trim($_POST['password'])));

//Input Validations
if($username == '') {
    $errmsg_arr[] = 'Username required';
    $errflag = true;
}
if($password == '') {
    $errmsg_arr[] = 'Password required';
    $errflag = true;
}

//If there are input validations, redirect back to the login form
if($errflag) {
    $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
    session_write_close();
    header("location: logon.php");
    exit();
}

//Load and run query
$result = mysqli_query($mysqli, "SELECT * FROM auth WHERE username='$username' AND password='$password'");

if ($result->num_rows) {
//Login Successful
        session_regenerate_id();
        //Set session variables
        $member = $result->fetch_assoc();
        $_SESSION['SESS_MEMBER_ID'] = $member['ID'];
        $_SESSION['SESS_USERNAME'] = $member['username'];
        $_SESSION['SESS_FIRST_NAME'] = $member['fname'];
        $_SESSION['SESS_PASSWORD'] = $member['password'];
        $_SESSION['SESS_AUTH_LEVEL'] = $member['auth_level'];
        session_write_close();
        header("location: index");
        exit();
    }else {
        //Login failed
        $errmsg_arr[] = 'user name or password not found';
        $errflag = true;
        if($errflag) {
            $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
            session_write_close();
            header("location: logon.php");
            exit();
        }
    }
mysqli_close($mysqli); 
?>

非常感谢!

1 个答案:

答案 0 :(得分:-1)

好吧,你想在这里使用预备语句,因为你没有执行静态 SQL查询 - 这就是要使用的mysqli_query()

所以,这就是你需要做的事情:

  1. 不要打扰// cleanup POST variables部分。
  2. 更改//Load and run query部分以使用预准备声明。
  3. 首先,我们要准备它:http://php.net/manual/en/mysqli.prepare.php

    $query = mysqli_prepare($mysqli, "SELECT * FROM auth WHERE username=? AND password=?");

  4. 那我们想给Mysqli什么的?标记是:http://www.php.net/manual/en/mysqli-stmt.bind-param.php

    $query->bind_param('ss', $username, $password);

  5. 然后,使用bind_resultfetch(请参阅http://www.php.net/manual/en/class.mysqli-stmt.php处的索引)获取结果并存储到会话变量中。