MySQL UTF-8 Character insert issue

2019-07-28 02:24发布

问题:

I am fetching some string from facebook , but i dont know whitch encoding in string . I need to convert this string into utf8 before inserting into database table . Getting this error message.

Here is my php code.

$email = (isset($this->_userinfo['email']) ? $this->_userinfo['email'] : '');
$fname = $this->_userinfo['first_name'];
$lname = $this->_userinfo['last_name'];
$name  = $this->_userinfo['name'];

$sql = 'INSERT INTO users '
     . '(fbid, fbuid, fullname, userlevel, email, name, sirname) '
     . 'VALUES("'
     . $this->_fbid . '","'
     . $fbuid . '","'
     . $name . '","' 
     . $userlevel . '","' 
     . $email . '","' 
     . $fname . '","' 
     . $lname . '")';

回答1:

You might want to take a look at this question:

Detect encoding and make everything UTF-8

especially the second answer by Sebastian Grinoli

He wrote a class (and offers the link to it) which would correctly encode Windows Extended ASCII to UTF8 and also correct UTF8 if necessary.

A really handy tool to have when you are in the UTF8 land :)



回答2:

did you try this code ?

   mysql_query('set names utf8'); 


回答3:

Take a look at utf8_encode to do this for you. Keep in mind this will only work if your data is actually UTF-8 encoded. Unfortunately there is no way to just look at the string and see what encoding it's using.



回答4:

enter link description here

For me works following code:

$mysqli = mysqli_connect( ... ); mysqli_query( $mysqli, 'SET NAMES "utf8" COLLATE "utf8_general_ci"' );

or just:

mysqli_set_charset( $mysqli, 'utf8' );

Regards, good luck!