How to convert latin1_swedish_ci data to utf8_bin in php?

Question:

I got a SQL script that "assembles" 3 tables, one with country, one with states and one with Brazilian cities. The script makes the collection of names in latin1_swedish_ci and I needed it to be utf8_bin , because names with accents generate another character, and I still have to put those names in json format.

My HTML:

<div align="center">
<form>
    <input type="hidden" ng-model="estado.idEstado">
    Estado <input type="text" ng-model="estado.nome">
    Sala <input type="text" ng-model="estado.sala">
    <button ng-click="atualizarEstado(estado)">Atualizar</button><br>
</form>

My php:

<?php
include_once("conPDO.php");
$pdo = conectar();

$id = $_GET['idEstado'];

$buscarEstado=$pdo->prepare("SELECT * FROM estado WHERE idEstado=:id ");
$buscarEstado->bindValue(":id", $id);
$buscarEstado->execute();

//header('Content-Type: application/json');

$return = array();

while ($linha=$buscarEstado->fetch(PDO::FETCH_ASSOC)) {
        $return = $linha;
        print_r($return);
}

echo json_encode($return);
?>

On the console appears this:

Array
    (
        [idEstado] => 4
        [nome] => Amap�
        [uf] => AP
        [pais] => 1
        [sala] => 
    )

Answer:

Run a query by setting the database charset

$pdo->query('SET NAMES UTF-8');

or if your bank is using ISO-8859-1

$pdo->query('SET NAMES LATIN1');
Scroll to Top