accentuation problem when saved in the database

Asked

Viewed 560 times

1

There’s a problem with me, when I save a value in the database, it saves without accentuation.

All my code on the page is utf8, all my database is utf8, the tables are utf8 and where does the Insert is utf8

When I put utf8_encode() in the code, it works, but when I reset the value, it comes with the same accentuation problem

public function cadastrarResponsavel(){
        try{
            $sql = "INSERT INTO $this->prt_partner_responsible(id_resp,nome,cargo,tel_comercial1,tel_comercial2,tel_celular1,tel_celular2,email1,email2,nota,_id_partner,_ativo,_data_registro )
VALUES (NULL,:nome,:cargo,:tel_comercial1,:tel_comercial2,:tel_celular1,:tel_celular2,:email1,:email2,:nota,:id_partner,:ativo,:data_registro)";
            $stmt = DB::prepare($sql);


            foreach($this->nomeResponsavel as $key => $values) {

                $stmt->bindParam(":nome", $this->nomeResponsavel[$key], PDO::PARAM_STR);
                $stmt->bindParam(":cargo", $this->cargoResponsavel[$key], PDO::PARAM_STR);
                $stmt->bindParam(":tel_comercial1", $this->telefoneComercial1Resp[$key], PDO::PARAM_STR);
                $stmt->bindParam(":tel_comercial2", $this->telefoneComercial2Resp[$key], PDO::PARAM_STR);
                $stmt->bindParam(":tel_celular1", $this->telefoneCelularIIResp[$key], PDO::PARAM_STR);
                $stmt->bindParam(":tel_celular2", $this->telefoneCelularIIResp[$key], PDO::PARAM_STR);
                $stmt->bindParam(":email1", $this->email1Resp[$key], PDO::PARAM_STR);
                $stmt->bindParam(":email2", $this->emaiI2Resp[$key], PDO::PARAM_STR);
                $stmt->bindParam(":nota", $this->comentariosResp[$key], PDO::PARAM_STR);
                $stmt->bindParam(":id_partner", $this->idParceiro, PDO::PARAM_STR);
                $stmt->bindParam(":ativo", $this->ativo, PDO::PARAM_STR);
                $stmt->bindParam(":data_registro", $this->datas, PDO::PARAM_STR);
                $stmt->execute();
            }
            return $stmt->rowCount();
        }catch (PDOException $ex){
            $Exc = new ExceptionDatabase();
            date_default_timezone_set('America/Sao_Paulo');
            $dataRegistro = date("Y-m-d H:i:s");
            $this->Caminho = explode("/", $_SERVER['SCRIPT_NAME']);
            $this->arquivo = $this->Caminho[count($this->Caminho)-1];
            $this->arquivoLog = 'log/erros.txt';
            $this->erro =  $ex->getCode();
            $this->mensagem  = $ex->getMessage();

            $Exc->setTipoLog(enum::Error);
            $Exc->setTitleLog($ex->errorInfo);
            $Exc->setDescLog($ex->getMessage());
            $Exc->setDataRegistro($dataRegistro);
            $Exc->setArquivo($this->arquivo);
            $Exc->setArquivoLog($this->arquivoLog);
            $Exc->setErro($this->erro);
            $Exc->setMensagem($this->mensagem);

            $Exc->erro();
        }
    }

Está utf8

He saves on the bench like this

Ele salva assim

Connecting querys

Basically I tried two ways

Setting utf8 in the config and calling in the DB class

header('Content-Type: text/html; charset=UTF-8'); //ja tinha esse header utf8
define('DB_HOST', 'host qualquer' ); //host
define('DB_NAME', 'banco de dados qualquer'); //nome do servidor
define('DB_USER', 'usuario qualquer');  // nome do usuario
define('DB_PASS', 'senha qualquer');   //nome da senha
define('DB_CHARSET','charset=utf8"');  //codificação

and set it in the connection class

require_once 'config.php';
class DB{
    private static $instance;
    public static function getInstance()
    {
        if(!isset(self::$instance))
        {
            try
            {
                self::$instance = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS,DB_CHARSET);
                //self::$instance->exec("set names utf8");
                self::$instance->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                self::$instance->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
            } catch (PDOException $e)
            {
                echo $e->getMessage();
            }
        }
        return self::$instance;
    }

    public static function prepare($sql){
        return self::getInstance()->prepare($sql);
    }
}

and also putting the exec straight, did not work

require_once 'config.php';
class DB{
    private static $instance;
    public static function getInstance()
    {
        if(!isset(self::$instance))
        {
            try
            {
                self::$instance = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS);
                self::$instance->exec("set names utf8");
                self::$instance->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                self::$instance->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

            } catch (PDOException $e)
            {
                echo $e->getMessage();
            }
        }
        return self::$instance;
    }


    public static function prepare($sql){
        return self::getInstance()->prepare($sql);
    }
}

nor executes inserir a descrição da imagem aqui

runs normally, but messes up all the coding inserir a descrição da imagem aqui

2 answers

1

Set the charset utf8 on the PDO connection.

Your connection string would look like this:

"mysql:host=$host;dbname=$db;charset=utf8"

If you are using an old PHP version, this command is ignored, then you should set it via command, like this:

$dbh = new PDO("mysql:$connstr",  $user, $password);
$dbh->exec("set names utf8");

Try performing this setup and see if it solves.

  • blz, I’m gonna try

  • did not work, nor runs the connection

  • After your change, how was your connection string? can send me to check?

  • I’ll edit my question.

  • Look @Bruno Rigolon, edited

  • Come on, try putting this line in place of your: self::$instance = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8', DB_USER, DB_PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'") );

  • he doesn’t even connect to the bank

  • actually connects but messes up the coding

  • Perfect, leave it at that, now check your page if it’s in UTF-8. @Sorack mentioned a post, I believe it’s related as well. You have to check the page (charset set set in the file), connection to the database and Charsets set.

  • Man, everything is in utf8, I’ve checked everything]

  • If nothing worked, I suggest you try to isolate the problem. Create a PHP file separate from everything, put the code of your class, make the connection and list the data and see if the problem will occur. In this file simulate the insertion of UTF8 data and without and see what will occur. According to this data you will get a better idea of what is occurring.

  • what you say, do a db, a table, connection, all test?

Show 8 more comments

0

Fixed problem, the error was when I tried to send the data with utf8_encode, since I had passed everything to utf8

Browser other questions tagged

You are not signed in. Login or sign up in order to post.