Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO Connection Password can't have $ # ! characters

Tags:

php

mysql

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

like image 652
Nima Avatar asked Dec 24 '22 15:12

Nima


1 Answers

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.

  • http://php.net/manual/en/function.error-reporting.php

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:

  • UTF-8 all the way through
like image 114
Funk Forty Niner Avatar answered Jan 06 '23 18:01

Funk Forty Niner