How can I escape special characters in a PDO connection string?(如何转义 PDO 连接字符串中的特殊字符?)
问题描述
我正在使用 PDO 扩展从 PHP 连接到 MariaDB 数据库.我想知道如何转义特殊字符以在连接字符串中使用.
I am using the PDO extension to connect to a MariaDB database from PHP. I would like to know how to escape special characters for use in the connection string.
明显的尝试(URL 编码,用单引号括起来)都失败了.
The obvious attempts (URL-encoding, enclosing in single quotes) all fail.
我目前不需要连接到例如一个名字奇怪的数据库,但我想知道以防万一.
I currently don't need to connect to e.g. a strangely-named database, but I would like to know how in case I do.
具体来说:假设我有以下 PHP 代码
Specifically: Suppose I have the following PHP code
<?php
$username = 'some user';
$password = 'some password';
$host = 'dummy.example.com';
$port = 1 << 16;
$dbname= 'alpha;a=b';
$PDO = new PDO("mysql:host=$host;port=$port;dbname=$dbname",
$username, $password, []);
这不起作用,因为 $dbname
中的分号被解释为元字符.我想知道如何转义这个角色.
This doesn't work because the semicolon in $dbname
is interpreted as a metacharacter. I would like to know how to escape this character.
推荐答案
如果出于某些奇怪的原因需要这样做,请不要在 dns.xml 中使用 dbname
参数.相反,请使用您的数据库驱动程序为您选择它:
If for some, strange reason you need to do this, don't use the dbname
parameter in the dns. Instead, use your database driver to select it for you:
$dbh->query('use "newdatabase"'); // for mysql.
这样,您可以选择用 "
将数据库名称括起来,因此您可以将其命名为驱动程序 允许.对于MySQL 对于这种特定情况,它是 "
字符,但这并不意味着它与 PostgreSQL 或 Firebase 不同.
This way, you have the option to enclose the database name with "
, so you can name it whatever the driver allows. For MySQL for this specific scenario it is the "
character, but that does not mean its different for PostgreSQL or Firebase.
但是这种方法不是万无一失的,它只允许 PDO 库正常解析 DSN,因为我不期望 PDO 库能够应对这种不寻常的情况,因为它的唯一目的是与尽可能多的司机互动.
But this method is not bulletproof, it only allows the PDO library to parse the DSN as normal as I don't expect the PDO library to cope with this unusual situation as its only purpose is to interact with as many drivers as possible.
驱动程序的特定津贴不应该参与PDO,所以你真的应该向驱动程序询问,这样你也可以检查查询是否执行失败.
Driver specific allowances should not take part in PDO, so you should really ask the driver for this, this way you can also check if the query fails to execute.
这篇关于如何转义 PDO 连接字符串中的特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何转义 PDO 连接字符串中的特殊字符?
基础教程推荐
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01