Almacenamiento y visualización de cadena unicode (हिन्दी) utilizando PHP y MySQL


Tengo que almacenar texto hindi en una base de datos MySQL, recuperarlo usando un script PHP y mostrarlo en una página web. Hice lo siguiente:

Creé una base de datos y establecí su codificación en UTF-8 y también la intercalación en utf8_bin. Agregué un campo varchar en la tabla y lo configuré para aceptar texto UTF-8 en la propiedad charset.

Luego me puse a agregar datos a ella. Aquí tuve que copiar datos de un sitio existente. El texto en hindi se ve así: {: 05: 30

I copié directamente este texto en mi base de datos y usé el código PHP echo(utf8_encode($string)) para mostrar los datos. Al hacerlo, el navegador me mostró "??????".

Cuando inserté el equivalente UTF del texto yendo a "ver fuente" en el navegador, sin embargo, translates se traduce en सूर्योदय.

Si entro y almaceno सूर्योदय en la base de datos, se convierte perfectamente.

Así que lo que quiero saber es cómo puedo almacenar directamente my en mi base de datos y recuperarla y mostrarla en mi página web utilizando PHP.

Además, ¿puede alguien ayudarme a entender si hay un script que cuando escribo सूर्योदय, me da सूर्योदय?

Solución Encontrada

Escribí el siguiente script de ejemplo que funcionó para mí. Espero que ayude a alguien más también

<html>
  <head>
    <title>Hindi</title></head>
  <body>
    <?php
      include("connection.php"); //simple connection setting
      $result = mysql_query("SET NAMES utf8"); //the main trick
      $cmd = "select * from hindi";
      $result = mysql_query($cmd);
      while ($myrow = mysql_fetch_row($result))
      {
          echo ($myrow[0]);
      }
    ?>
  </body>
</html>

El volcado para mi base de datos que almacena cadenas utf hindi es

CREATE TABLE `hindi` (
  `data` varchar(1000) character set utf8 collate utf8_bin default NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `hindi` VALUES ('सूर्योदय');

Ahora mi pregunta es, ¿cómo funcionó sin especificar "META" o información de encabezado?

Gracias!

Author: Svante, 2009-07-29

4 answers

¿Ha establecido un conjunto de caracteres adecuado en la sección HTML Head?

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

O puede establecer el tipo de contenido en su script php usando -

   header( 'Content-Type: text/html; charset=utf-8' ); 

Ya hay algunas discusiones aquí sobre StackOverflow-por favor, eche un vistazo

Cómo hacer que MySQL maneje UTF-8 correctamente configurando utf8 con mysql a través de php

PHP / MySQL con problemas de codificación

Así que lo que quiero saber es cómo puedo directamente almacenar my en mi base y buscarlo y mostrar en mi página web usando PHP.

No estoy seguro de lo que quiere decir con "almacenar directamente en la base de datos" .. ¿te referías a introducir datos usando phpMyAdmin o cualquier otra herramienta similar? Si es así, he intentado usar phpMyAdmin para ingresar datos unicode, por lo que ha funcionado bien para mí - Podría intentar ingresar datos usando phpmyadmin y recuperarlos usando un script php para confirmar. Si necesita enviar datos a través de un script Php, simplemente establezca los NOMBRES y el CONJUNTO de CARACTERES cuando cree mysql conexión, antes de ejecutar consultas de inserción y cuando seleccione datos. Echa un vistazo a las publicaciones anteriores para encontrar la sintaxis. Espero que ayude.

* * ACTUALIZAR ** Acabo de corregir algunos errores tipográficos, etc

 36
Author: TigerTiger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:47
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">


<?php 
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_query('SET character_set_results=utf8');
mysql_query('SET names=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_results=utf8');
mysql_query('SET collation_connection=utf8_general_ci');

mysql_select_db('onlinetest',$con);

$nith = "CREATE TABLE IF NOT EXISTS `TAMIL` (
  `data` varchar(1000) character set utf8 collate utf8_bin default NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1";

if (!mysql_query($nith,$con))
{
  die('Error: ' . mysql_error());
}

$nithi = "INSERT INTO `TAMIL` VALUES ('இந்தியா நாட்டின் பக்கங்கள்')";

if (!mysql_query($nithi,$con))
{
  die('Error: ' . mysql_error());
}

$result = mysql_query("SET NAMES utf8");//the main trick
$cmd = "select * from TAMIL";
$result = mysql_query($cmd);
while($myrow = mysql_fetch_row($result))
{
    echo ($myrow[0]);
}
?>
</body>
</html>
 21
Author: ROSE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-27 04:09:38

Para aquellos que están buscando PHP ( >5.3.5 ) declaración PDO, podemos establecer charset como abajo:

$dbh = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
 3
Author: Sandeep,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-02 12:59:45
CREATE DATABASE hindi_test
CHARACTER SET utf8
COLLATE utf8_unicode_ci;
USE hindi_test;
CREATE TABLE `hindi` (`data` varchar(200) COLLATE utf8_unicode_ci NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `hindi` (`data`) VALUES('कंप्यूटर');
 1
Author: Vinod Tiwari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-29 19:18:20