dongpu5600 2017-07-20 20:31
浏览 389
已采纳

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

I use ! @ # $ in my MySQL user's password

but when using these characters in my password, PDO can't connect to MySQL server

$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)

when removing !@#$ from password it works correctly

  • 写回答

1条回答 默认 最新

  • doukuanghuan7582 2017-07-20 20:43
    关注

    This has nothing to do with UTF-8.

    PHP thinks you have a variable name with a $ assigned to it.

    The $password = "!@#$test"; with the double quotes is technically looking for a variable called $test and is trying to parse it.

    It needs to be in single quotes:

    $password = '!@#$test';
    

    Note: The ! and @ also have special meaning in PHP.

    • ! is 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.

    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.

    This is covered in the following Q&A:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)