本文介绍了如何从mysql_ *升级到mysqli_ *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用不推荐使用的代码从用户获取数据,如下所示:

I'm currently using deprecated code to get data from users, as follows:

/* retrieve */
$lastName = $_POST['lastName'];
$firstName = $_POST['firstName'];
$examLevel=$_POST['level'];

/* connect */
$dbc=mysql_connect("localhost", "user", "passw") or die('Error connecting to MySQL server');
mysql_select_db("db") or die('Error selecting database.');

/* sanitize */
$lastName=mysql_real_escape_string($lastName);
$firstName=mysql_real_escape_string($firstName);
$examLevel=mysql_real_escape_string($examLevel);


/* insert */
$query_personal = "INSERT INTO personal (LastName, FirstName) VALUES  ('$lastName', '$firstName')";

$query_exam = "INSERT INTO exam (Level, Centre, BackupCentre, etc.) VALUES ('$examLevel', '$centre', '$backup', 'etc')";

这是有效的,但我不断遇到有关安全性和缺乏支持的警告.有一个小的重写可以用mysqli代替mysqli connect ,但是 mysqli_real_escape_string 呢?我已经在示例中看到了它,但是我也看到了使用不带mysqli_real_escape_string的准备好的语句的建议.

This is working but I keep coming across warnings about security and lack of support. There's a small rewrite to connect with mysqli instead of mysql but what about mysqli_real_escape_string? I've seen it used in examples but I've also seen advice to use prepared statements instead which don't use mysqli_real_escape_string.

我将如何使用准备好的语句来插入我的数据?到目前为止,我有点在海上.例如,参数绑定仅用于INSERT,结果绑定仅用于SELECT吗?

And how would I use prepared statements to INSERT my data? I'm a bit at sea with this bit so far. For example, is parameter binding only for INSERTs and result binding only for SELECTs?

推荐答案

将其转换为 PDO

/* connect */
$dsn = "mysql:host=localhost;db=test;charset=utf8";
$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,"user", "passw", $opt);


/* insert */
$query = "INSERT INTO personal (LastName, FirstName) VALUES  (?, ?)";
$stmt  = $pdo->prepare($query);
$stmt->execute(array($_POST['lastName'],$_POST['firstName']));

$query = "INSERT INTO exam (Level, Centre, BackupCentre, etc) VALUES (?, ?, ?, 'etc')";
$stmt  = $pdo->prepare($query);
$stmt->execute(array($_POST['level'], $centre, $backup));

这篇关于如何从mysql_ *升级到mysqli_ *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 15:12