简体   繁体   English

PDO连接密码不能有$#! 人物

[英]PDO Connection Password can't have $ # ! characters

I use ! 我用 ! @ # $ in my MySQL user's password 我的MySQL用户密码中的@#$

but when using these characters in my password, PDO can't connect to MySQL server 但是在我的密码中使用这些字符时,PDO无法连接到MySQL服务器

$servername = "localhost";
$username = "test";
$password = "!@#$test";
$dbname = "test";

try {
  $test = $_POST['test'];
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, 
  $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  // prepare sql and bind parameters
  $stmt = $conn->prepare("INSERT INTO test (test) 
  VALUES (:test)");
  $stmt->bindParam(':test', $test);


  $stmt->execute();

It gives this error: 它给出了这个错误:

SQLSTATE[HY000] [1045] Access denied for user 'test'@'localhost' (using password: YES) SQLSTATE [HY000] [1045]拒绝访问用户'test'@'localhost'(使用密码:YES)

when removing !@#$ from password it works correctly 从密码中删除!@#$时,它可以正常工作

This has nothing to do with UTF-8. 这与UTF-8无关。

PHP thinks you have a variable name with a $ assigned to it. PHP认为你有一个变量名称,并为其分配了$

The $password = "!@#$test"; $password = "!@#$test"; with the double quotes is technically looking for a variable called $test and is trying to parse it. 使用双引号在技术上寻找一个名为$test的变量,并试图解析它。

It needs to be in single quotes: 它需要用单引号:

$password = '!@#$test';

Note: The ! 注意: ! and @ also have special meaning in PHP. @在PHP中也有特殊含义。

  • ! is not . not
  • @ is an error suppressor and a character used in email. @是错误抑制器和电子邮件中使用的字符。
  • # is a comment character. #是评论字符。

Theoretically, error reporting should have thrown you a notice about an undefined variable. 从理论上讲,错误报告应该会让你注意到一个未定义的变量。

UTF-8 deals with queries and characters that won't display correctly when querying, depending on the db's/table's collation. UTF-8处理查询时无法正确显示的查询和字符,具体取决于db / table的排序规则。

If and when that you start seeing ? 如果你?时候开始看到? in your query's output, then you would need to set the connection's DSN to UTF-8. 在查询的输出中,您需要将连接的DSN设置为UTF-8。

This is covered in the following Q&A: 这包含在以下问答中:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM