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
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With