Problem in database connection

Asked

Viewed 221 times

0

I am changing a code from a news system that came with charset iso... Now I intend to change it to utf8.

I have already managed to appear in utf8 on the page where the news are presented.inserir a descrição da imagem aqui

Now the problem is when I load in read more.inserir a descrição da imagem aqui

I already changed the tables to utf8 and work with the pages in utf8, I think the problem is in the connection.

I have two files inside a folder called database.

database conf.

<?php

global $databases;
$databases = array( 
    'local' => array
    (
            'host'=>'localhost',
            'port'=>3306,
            'dbname'=>'noticias',
            'user'=>'root',
            'password'=>''
    )
);

/* end file */

and mysql.php

<?php

Class mysql
{

    public $query;
    public $data;
    public $result;
    public $rows;   
    public $page = 0;
    public $perpage = 10;
    public $current = 1;
    public $url;
    public $link = '';
    public $total = '';
    public $pagination = false;


    protected $config;
    protected $host;
    protected $port;
    protected $user;
    protected $pass;
    protected $dbname;
    protected $con;



    public function __construct()
    {
        try
        {
            #array com dados do banco
            include 'database.conf.php';
            global $databases;
            $this->config = $databases['local'];
            # Recupera os dados de conexao do config
            $this->dbname = $this->config['dbname'];
            $this->host = $this->config['host'];
            $this->port = $this->config['port'];
            $this->user = $this->config['user'];
            $this->pass = $this->config['password'];




            # instancia e retorna objeto
            $this->con = mysql_connect( "$this->host", "$this->user", "$this->pass" );
            mysql_select_db( "$this->dbname" );
            if ( !$this->con )
            {
                throw new Exception( "Falha na conexão MySql com o banco [$this->dbname] em database.conf.php" );
            }
            else
            {
                return $this->con;
            }
            $this->url = $_SERVER['SCRIPT_NAME'];
        }
        catch ( Exception $e )
        {
            echo $e->getMessage();
            exit;
        }
        return $this;
    }

    public function query( $query = '' )
    {
        try
        {
            if ( $query == '' )
            {
                throw new Exception( 'mysql query: A query deve ser informada como parâmetro do método.' );
            }
            else
            {
                $this->query = $query;
                if($this->pagination == true){  
                    mysql_query("SET NAMES 'utf8'");
                    mysql_query('SET character_set_connection=utf8');
                    mysql_query('SET character_set_client=utf8');
                    mysql_query('SET character_set_results=utf8');
                    $this->result = mysql_query( $this->query );
                    $this->fetchAll();
                    $this->paginateLink();
                    $this->query .= " LIMIT $this->page, $this->perpage";
                    $this->pagination = false;
                }
                $this->result = mysql_query( $this->query );

            }
        }
        catch ( Exception $e )
        {
            echo $e->getMessage();
            exit;
        }
        return $this;
    }

    public function fetchAll()
    {
        $this->data = "";
        $this->rows = 0;
        while ( $row = mysql_fetch_array( $this->result, MYSQL_ASSOC ) )
        {

            $this->data[] = $row;
        }
        if ( isset( $this->data[0] ) )
        {
            $this->rows = count( $this->data );
        }
        return $this->data;
    }

    public function rowCount()
    {
        return @mysql_affected_rows();
    }    

    public function getUrl($perpage)
        {
            $this->url = $_SERVER['REQUEST_URI'];
            return $this;
        }   
        public function paginate($perpage)
        {
            $this->pagination = true;
            $this->perpage = $perpage;
            return $this;
        }
        public function paginateLink()
        {   
            if(!preg_match('/\?/',$this->url))
            {
                $this->url .= "?";
            }else{
                $this->url .= "&";
            }
            if ( isset( $_GET['page'] ) )
            {
                $this->current = $_GET['page'];
                $this->page = $this->perpage * $_GET['page'] - $this->perpage;
                if ( $_GET['page'] == 1 )
                {
                    $this->page = 0;
                }
            }
            $this->total = $this->rows;
            if ( $this->rows > $this->perpage )
            {                           
                $this->link = "<div class=\"pagination\"><ul>";
                $prox = "javascript:;";
                $ant = "javascript:;";
                if ( $this->current >= 2 )
                {
                    $ant = $this->url."page=" . ($this->current - 1);
                }
                if ( $this->current >= 1 && $this->current < ($this->total / $this->perpage))
                {
                    $prox = $this->url."page=" . ($this->current + 1);
                }
                $this->link .= '<li><a href="' . $ant . '">&laquo;</a></li>';
                $from = round( $this->total / $this->perpage );
                if($from == 1){$from++;}

                for ( $i = 1; $i <= $from ; $i++ )
                {
                    if ( $this->current == $i )
                    {
                        $this->link .= "<li class=\"active\"><a>$i</a></li>\n";
                    }
                    else
                    {
                        $this->link .= "<li><a href=\"".$this->url."page=$i\">$i</a></li>\n";
                    }
                }
                $this->link .= '<li><a href="' . $prox . '">&raquo;</a></li>';
                $this->link .= "</ul>\n";
                $this->link .= "</div>\n";
            }   
            return $this;
        }

        public function cut($str,$chars,$info=  '')
        {
            if ( strlen( $str ) >= $chars )
            {
                $str = preg_replace( '/\s\s+/', ' ', $str );
                $str = strip_tags( $str );
                $str = preg_replace( '/\s\s+/', ' ', $str );
                $str = substr( $str, 0, $chars );
                $str = preg_replace( '/\s\s+/', ' ', $str );
                $arr = explode( ' ', $str );
                array_pop( $arr );
                //$arr = preg_replace('/\&nbsp;/i',' ',$arr);
                $final = implode( ' ', $arr ) . $info;
            }
            else
            {
                $final = $str;
            }
            return $final;
        }

    }


    /* end file */

I had added these lines in the query function:

                mysql_query("SET NAMES 'utf8'");
                mysql_query('SET character_set_connection=utf8');
                mysql_query('SET character_set_client=utf8');
                mysql_query('SET character_set_results=utf8');

with these I got the news listed in utf8.

Now I intend that when you click to read more the news also present itself in utf8.

  • You change the bank charset and force a new one with SET is gambiarra. You patch with header() is more gambiarra yet. You fill your final code with utf8_encode() / utf8_decode() is the suprassumo of the gambiarra, record type at the stop, besides being harmful for the performance of your Application.. What you should do is re-edit each article, each text, link and etc. Of course it doesn’t need to be manually, you can create a Cronjob that does conversions with iconv and do the in Updates.

2 answers

2

Since the sql language is sequential, it can only be a query function positioning problem.

Try to relocate the darlings

mysql_query("SET NAMES 'utf8'");
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');

shortly after the include 'database.conf.php';

Or even better: include these queries INSIDE the connection file, right after the mysql_select_db

0


The error in your script is at the time of connection. Soon after connecting you must use the command SET NAMES utf8; This command is only required once per connection, so there is no need to use it every query run;

Notice also about the depreciation of mysql functions_*

Use the functions whenever possible mysqli_* or else the PDO;

Behold in this post because we should no longer use the mysql functions_*

Browser other questions tagged

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