CD_NS
CD_NS

Reputation: 319

Error connecting to mysql database.

It might be a duplicate, but i went through all the solution that are suggested in other posts at stackoverflow but cannot find a solution.

 <?php
$PDO= new PDO('mysql:host= 127.0.0.1; dbname = social_network; charset= utf8', 'root', '' );
$PDO-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

?>

The error i am having is as follows:

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2019] Unknown character set in C:\xampp\htdocs\social_network\create_account.php:2 Stack trace: #0 C:\xampp\htdocs\social_network\create_account.php(2): PDO->__construct('mysql:host= 127...', 'root', '') #1 {main} thrown in C:\xampp\htdocs\social_network\create_account.php on line 2

I appreciate your quick asnwer.

Upvotes: 3

Views: 12924

Answers (4)

You have an extra extra space in the DSN which is count as a part of charset name, so it has to be removed.

<?php
$servername = 127.0.0.1;  //localhost
$username = "root";
$password = "";
$dbname = "social_network";
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Upvotes: 6

you just have to remove the white space in "charset= utf8". So you would have "charset=utf8".

Upvotes: 3

newenthusiasts
newenthusiasts

Reputation: 11

For the charset need to be specific which is being used in XAMPP/WAMP.

You can change charset=utf8 To charset=utf8mb4

Upvotes: 1

Mame Medoune Diop
Mame Medoune Diop

Reputation: 322

$host = '127.0.0.1';
$database = 'social_network';
$user = 'root';
$password = '';
$charset = 'utf8';
$options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false
    ];
$dsn = "mysql:host=$host;dbname=$database;charset=$charset";
$db = new PDO($dsn, $user, $password, $options);

This should work! Check this url (https://phpdelusions.net/pdo) PDO is better explained there! Your issus is about the charset

Upvotes: 0

Related Questions