How to upgrade from mysql_* to 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_*?
基础教程推荐
- 超薄框架REST服务两次获得输出 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在多维数组中查找最大值 2021-01-01