Search code examples
phpmysql

How to set UTF8 charset in connection with connection to MYSQL Database


I would like to establish a connection to my MYSQL database. Unfortunately, I haven't found the right one for me anywhere. Does anyone have a solution that is similar to this one?

I have tried this but i want to have utf 8 to charset and it does not work

`
`    <?php
$servername = "localhost";
$username = "u123456789_User";
$password = "MyStr0ngPa$!";

$conn = mysqli_connect($servername, $username, $password);

if (!$conn) {

    die("Connection failed: " . mysqli_connect_error());

}
echo "Connected successfully";
mysqli_close($conn);
?>
`
`

Solution

  • try it with:

    <?php
    $server = 'localhost:3306';
    //or localhost: 127.0.0.1:3306
    $username = 'root';
    $password = '';
    $schema = '';
    
    try{
        $conn = new PDO('mysql:host='.$server.';dbname='.$schema.';charset=utf8',$user, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(Exception $e){
        echo "Connection failed: " . $e->getMessage();
    }
    ?>