Juan De la Cruz
Juan De la Cruz

Reputation: 465

Display HTML friendly special characters with PHP from a MySQL db

I'm from Mexico, so our strings contain some special characters that need to be stored and later displayed. Is there a way (using PHP) to encode a string from MySQL and use it in html?

  <?php 
    function especialidades($dbcesp){
        $q="SELECT NombreEspecialidad FROM especialidad;";
        $r=mysqli_query($dbcesp, $q);

        while ($esp=mysqli_fetch_assoc($r)) {
            ?>
            <button type="button" class="btn btn-default"><?php echo $esp['NombreEspecialidad']; ?></button>
            <?php
        }
    } 
   ?>

This is the way I retrieve and generate some buttons for my webpage, but for some reason, aren't displayed correctly.

Upvotes: 1

Views: 1445

Answers (3)

Juan De la Cruz
Juan De la Cruz

Reputation: 465

I had to change the database collation to utf8_spanish_ci (during database creation in PHPMyAdmin).

Also, I had to add the charset meta tag to the html document:

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

And finally, I used the PHP encode api, being used as follows:

  <?php 
function especialidades($dbcesp){
    $q="SELECT * FROM especialidad;";
    $r=mysqli_query($dbcesp, $q);

    while ($esp=mysqli_fetch_assoc($r)) {
        ?>
        <a href="?page=6&esp=<?php echo $esp['CveEspecialidad']; ?>">
        <button type="button" class="btn btn-default" value="<?php echo $esp['CveEspecialidad']; ?>">

                <?php
                    echo utf8_encode($esp['NombreEspecialidad']); 
                ?>

        </button>
        </a>
        <?php
    }
} 
?>

This worked for me

Upvotes: 0

auth private
auth private

Reputation: 1316

first go to your phpmyadmin then set Server connection collation to utf8mb4_general_ci

then select your database name then press on your table then press on structure you will see all columns inside your table go and change all columns using type varchar or text then go press on change the change the collation to utf8_general_ci then save then try to input another entry to your database it will be clearly now without any fuzzing words

and the top of your code type

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

and those lines in the top of your php code to define the utf charset

mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET utf8");
header("Content-Type: text/html; charset=UTF-8");

Upvotes: 3

kala4ek
kala4ek

Reputation: 113

You should configure database for using UTF-8. Also don't forget to set encoding on html to UTF-8 too.

Also, check the following link: MySql spanish character data

Upvotes: 1

Related Questions