我正在从MySQL迁移到mysqli。根据我的阅读,最好使用对我来说不熟悉的准备好的陈述。
原文:
$row = mysql_fetch_assoc(mysql_query("SELECT id,user,pass,email,timezone,lastIP,currIP,dtLastLogin,dtCurrLogin FROM test_users WHERE user='".$user."'"));
$_SESSION['id']= $row['id'];
$_SESSION['user']= $row['user'];
$_SESSION['pass'] = $row['pass'];
$_SESSION['timezone'] = $row['timezone'];
$_SESSION['email'] = $row['email'];
$_SESSION['lastIP'] = $row['lastIP'];
$_SESSION['currIP'] = $row['currIP'];
$_SESSION['dtLastLogin'] = $row['dtLastLogin'];
$_SESSION['dtCurrLogin'] = $row['dtCurrLogin'];
为什么我不应该使用它:
$sql = mysqli_fetch_assoc(mysqli_query($con,"SELECT id,user,pass,email,timezone,lastIP,currIP,dtLastLogin,dtCurrLogin FROM test_users WHERE user='".$user."'"));
//close connection
mysqli_close($con);
$_SESSION['id']= $sql['id'];
$_SESSION['user']= $sql['user'];
$_SESSION['pass'] = $sql['pass'];
$_SESSION['timezone'] = $sql['timezone'];
$_SESSION['email'] = $sql['email'];
$_SESSION['lastIP'] = $sql['lastIP'];
$_SESSION['currIP'] = $sql['currIP'];
$_SESSION['dtLastLogin'] = $sql['dtLastLogin'];
$_SESSION['dtCurrLogin'] = $sql['dtCurrLogin'];
但请使用此...假设它们的格式正确:
$sql='SELECT id,user,pass,email,timezone,lastIP,currIP,dtLastLogin,dtCurrLogin FROM test_users WHERE user = ?';
// prepare statement
$stmt = $con->prepare($sql);
// bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s',$user);
// execute statement
$stmt->execute();
// results to array
$rs=$stmt->get_result();
$arr = $rs->fetch_all(MYSQLI_ASSOC);
// close statement
$stmt->close();
//close connection
mysqli_close($con);
$_SESSION['id']= $arr['id'];
$_SESSION['user']= $arr['user'];
$_SESSION['pass'] = $arr['pass'];
$_SESSION['timezone'] = $arr['timezone'];
$_SESSION['email'] = $arr['email'];
$_SESSION['lastIP'] = $arr['lastIP'];
$_SESSION['currIP'] = $arr['currIP'];
$_SESSION['dtLastLogin'] = $arr['dtLastLogin'];
$_SESSION['dtCurrLogin'] = $arr['dtCurrLogin'];
我今天已经做了很多阅读...似乎我看过的所有地方,包括这里,有不同的方式做同样的事情。除了速度增加(读这个),我期待我更安全(再次,为了安全,我正在阅读mysqli是要走的路)。我想我有点困惑,这也更加安全。
例如,为什么要接受用户输入,如$ user = mysql_real_escape_string($ _ POST ['username']);不赞成这种方法,你不赞成这种方法吗?