Marc
Marc

Reputation: 9567

PHP charset issue while inserting data to mysql

I have a PHP file which inserts $mail and $password in my database. See code below. My php file, my BD and my table fields are in utf-8. So what I do not understand is why the mail I send "Philémon" goes as "Philémon" in my table. By the way I know it is not a mail format. It is just for the sake of testing.

My PHP:

<?php
header('Content-Type: text/html; charset=utf-8');
require("php/connect.inc.php");

$mail = mysql_real_escape_string("Philémon");
$password = sha1("pass123");

mysql_query("INSERT INTO ENS_MEMBRES (ENS_MAIL, ENS_PASS) VALUES ('$mail','$password')");
?>

Upvotes: 1

Views: 1123

Answers (2)

Sravan
Sravan

Reputation: 2019

For users currently experiencing this issue, mysql_query has been deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0 instead mysqli_query(procedural) or PDO can be used(refer php documentation). To fix this issue for users implementing procedural extension, try this

$conn = mysqli_connect('host', 'user', 'password', 'dbname');
mysqli_set_charset($conn,"utf8");

This worked perfectly for me!

For users implementing PDO extension, try the following

$pdo = new PDO(
    ''mysql:host=host;dbname=urdbname'',
    "username",
    "password",
    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); 

Hope this helps someone out there ;)

Upvotes: 0

Pekka
Pekka

Reputation: 449783

Your PHP source code is probably UTF-8 encoded; your database connection is probably ISO-8859-1 encoded, it's the default connection encoding of mySQL. That will cause the UTF-8 é to be interpreted as two separate bytes, and stored that way in your mySQL table.

Solution: do a

 mysql_set_charset('utf8'); 

before sending the data; if that function isn't available, use

mysql_query("SET NAMES utf8;");

Upvotes: 5

Related Questions