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:

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

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来