Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type of Collation I have to use for Spanish characters in my data base?

Tags:

html

database

php

I need to store a table with questions and answer in spanish in my data base, but the problem I have been encountering is that any way I try I'm not been able to have the special characters in the spanish alphabet (¿,ñ, á, é, etc.) display in my string output. With some character I see there are in my data base (á, é, í, ó, ú) but not display in my string. The ¿ cannot even been enter to my db. Then the ñ is not in my db instead I see a ? symbol. and in all the cases my strings in the php file output comes as null. what should I do to fix this and get proper output? Thanks.

here is how my db looks like:

enter image description here

here is a the code I use in my php file

<?php

$databasehost = "localhost";
$databasename = "Cuestionario";
$databaseusername ="user";
$databasepassword = "password";

$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or  die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());

$query = "SELECT * FROM Cuestionario_Spanish";
$sth = mysql_query($query);

if (mysql_errno()) { 
header("HTTP/1.1 500 Internal Server Error");
echo $query.'\n';
echo mysql_error(); 
}
else
{
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $rows[] = $r;
}
print json_encode($rows);
}

?>  

and this is the result I get:

enter image description here

like image 329
zvzej Avatar asked Dec 30 '25 06:12

zvzej


1 Answers

You just need to define charset.

<?php

$databasehost = "localhost";
$databasename = "Cuestionario";
$databaseusername ="user";
$databasepassword = "password";

$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or  die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
mysql_query("SET NAMES 'utf8'"); //This will FORCE SET CHARSET to utf-8

$query = "SELECT * FROM Cuestionario_Spanish";
$sth = mysql_query($query);

if (mysql_errno()) { 
header("HTTP/1.1 500 Internal Server Error");
echo $query.'\n';
echo mysql_error(); 
}
else
{
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $rows[] = $r;
}
print json_encode($rows);
}

?>  

Enjoy! :)

like image 60
Karma Avatar answered Dec 31 '25 19:12

Karma