沃梦达 / 编程问答 / php问题 / 正文

如何从 mysql_* 升级到 mysqli_*?

How to upgrade from mysql_* to mysqli_*?(如何从 mysql_* 升级到 mysqli_*?)

本文介绍了如何从 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 而不是 mysql 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_*?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何从 mysql_* 升级到 mysqli_*?

基础教程推荐