Najah Mousa Najah Mousa - 1 month ago 10
PHP Question

send and retrive arabic data from mysql database

I want to bring Arabic data from mysql database I wrote the php code but it gives me ????? on arabic data any help to make it wokrs ??

<?php header('Content-Type: charset=utf-8');
$link=mysqli_connect("localhost","root","","arabicd");
mysql_set_charset('utf8',$link);
if (mysqli_connect_errno($link))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysql_query("SET character_set_results = 'utf8'");
mysql_query("character_set_client = 'utf8'");
mysql_query("character_set_connection = 'utf8'");
mysql_query("character_set_database = 'utf8'");
$result = mysqli_query($link,"SELECT question,answer FROM ask ");
while ($row = mysqli_fetch_array($result))
{
$output[]=$row;
}
print(json_encode($output));

if($data){
echo $data;
}
mysqli_close($con);
?>

Answer
  • Though you can just use set names utf8 instead of all that creepy queries, there is nothing here wrong about Arabic, cheers :)
  • You are mixing mysql_* and mysqli_* which is not allowed
  • Even if it's allowed to use mysql & mysqli connections interchangeably, you are passing parameters toquery functions in an order that is different from expected
  • You should exit the script in case of connection failure (or do what ever, just change the execution flow)
  • That line print(json_encode($output)); is error prone, what if there are no results came from the table ? the loop will never be entered and $output will not be defined, so you must initialize $output with empty array, it's also a good practice to check if the result set is empty and handle it in a separate block
  • Also, it's preferred to enclose table names and columns in back ticks (`) in case that a column has a name of a reserved keyword

Here is a working version of your code after fixing errors

<html>

<meta charset="utf-8">
<?php 



$link = mysql_connect("localhost","root","");
if ($link === false)
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    exit;
}
mysql_select_db("arabicd", $link);
mysql_query("SET NAMES utf8");

$result = mysql_query("SELECT `ask`.`question`,`ask`.`answer` FROM `ask` ", $link);
$output = array();
while ($row = mysql_fetch_array($result))
{
    $output[]=$row;
}

print(json_encode($output));

if(isset($data))
{
	echo $data;
}

mysql_close($link);
?>
</html>

Comments