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

如何转义 PDO 连接字符串中的特殊字符?

How can I escape special characters in a PDO connection string?(如何转义 PDO 连接字符串中的特殊字符?)

本文介绍了如何转义 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 连接字符串中的特殊字符?

基础教程推荐