Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

plarruda

Erro mysql-connect

Recommended Posts

Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\fisioclinsm07\artigos\database\mysql.php on line 45

 

Já tentei substituir a linha 45 por mysqli_connect porem não deu certo.

Compartilhar este post


Link para o post
Compartilhar em outros sites

O que deu de errado ao substituir?

Compartilhar este post


Link para o post
Compartilhar em outros sites

aparece o seguinte erro na linha de baixo após também substituir por mysqli

 

Warning: mysqli_select_db() expects exactly 2 parameters,

 

Tem alguma forma do wampserver aceitar o mysql. Porque eu testei na web e não ocorreu erro algum, apenas no wampserver 2.5 esta dando este erro.


linha45 $this->con = mysqli_connect( "$this->host", "$this->user", "$this->pass" );
linha46 mysqli_select_db( "$this->dbname" );

 

erro referente a linha 46: Warning: mysqli_select_db() expects exactly 2 parameters,

Compartilhar este post


Link para o post
Compartilhar em outros sites

O problema está bem descrito, espera exatamente 2 parâmetros, você está passando apenas 1.

 

http://php.net/manual/en/mysqli.select-db.php

Compartilhar este post


Link para o post
Compartilhar em outros sites

aparece o seguinte erro na linha de baixo após também substituir por mysqli

 

Warning: mysqli_select_db() expects exactly 2 parameters,

 

Tem alguma forma do wampserver aceitar o mysql. Porque eu testei na web e não ocorreu erro algum, apenas no wampserver 2.5 esta dando este erro.

linha45 $this->con = mysqli_connect( "$this->host", "$this->user", "$this->pass" );

linha46 mysqli_select_db( "$this->dbname" );

 

erro referente a linha 46: Warning: mysqli_select_db() expects exactly 2 parameters,

 

 

 

 

Tive esse mesmo problema quando migrei do " mysql para mysqli ", não sou expert em programação , mas como os amigos aí de cima citaram o próprio erro diz espera 2 parâmetros:

 

Faz assim:

 

Em vez de :

 

linha45 $this->con = mysqli_connect( "$this->host", "$this->user", "$this->pass" );

linha46 mysqli_select_db( "$this->dbname" );

 

 

 

Se eu não estiver errado sua conexão é modo procedural:

 

Deixe assim : $this->con = new mysqli ( "$this->host", "$this->user", "$this->pass","$this->dbname" );

 

 

 

retire este trecho de código (mysqli_select_db( ) ;) e deixe tudo na mesma linha da conexão Nessa mesma situação fiz isso e deu certo pela lógica..

 

Para os mais experientes me corrijam se eu estiver errado, também tenho algumas dúvidas sobre isso.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Eu fiz como você disse acima porem apareceu outros erros.

 

( ! ) Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\wamp\www\fisioclinsm07\artigos\database\mysql.php on line 77 Call Stack # Time Memory Function Location 1 0.0009 247928 {main}( ) ..\noticias.php:0 2 0.0043 307184 mysql->query( ) ..\noticias.php:20 3 0.0043 307184 mysqli_query ( ) ..\mysql.php:77

 

( ! ) Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in C:\wamp\www\fisioclinsm07\artigos\database\mysql.php on line 98 Call Stack # Time Memory Function Location 1 0.0009 247928 {main}( ) ..\noticias.php:0 2 0.0043 307184 mysql->query( ) ..\noticias.php:20 3 0.0454 307552 mysql->fetchAll( ) ..\mysql.php:78 4 0.0454 307680 mysqli_fetch_array ( ) ..\mysql.php:98

 

( ! ) Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\wamp\www\fisioclinsm07\artigos\database\mysql.php on line 83 Call Stack # Time Memory Function Location 1 0.0009 247928 {main}( ) ..\noticias.php:0 2 0.0043 307184 mysql->query( ) ..\noticias.php:20 3 0.0696 308256 mysqli_query ( ) ..\mysql.php:83

 

( ! ) Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in C:\wamp\www\fisioclinsm07\artigos\database\mysql.php on line 98 Call Stack # Time Memory Function Location 1 0.0009 247928 {main}( ) ..\noticias.php:0 2 0.0932 308048 mysql->fetchAll( ) ..\noticias.php:20 3 0.0932 308192 mysqli_fetch_array ( ) ..\mysql.php:98

 

 

 

Preciso converter esse código para mysqli

Meu codigo 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 = mysqli_connect( "$this->host", "$this->user", "$this->pass", "$this->dbname" );
            //mysqli_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){ 
$this->result = mysqli_query( $this->query );
$this->fetchAll();
$this->paginateLink();
$this->query .= " LIMIT $this->page, $this->perpage";
$this->pagination = false;
}
                $this->result = mysqli_query( $this->query );
            }
        }
        catch ( Exception $e )
        {
            echo $e->getMessage();
            exit;
        }
        return $this;
    }


    public function fetchAll()
    {
        $this->data = "";
        $this->rows = 0;
        while ( $row = mysqli_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 . '">«</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 . '">»</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('/\ /i',' ',$arr);
            $final = implode( ' ', $arr ) . $info;
        }
        else
        {
            $final = $str;
        }
        return $final;
    }


}


/* end file */

Compartilhar este post


Link para o post
Compartilhar em outros sites

Então man fiz outras modificações e deixei como estava, apenas troquei lá no topo o Class mysql por abstract class con, e acrescentei um parâmetro na condição do mysqli_select_db($this->dbname); ficando assim mysqli_select_db($this->dbname,$this->con);..

 

Não sou expert em php, mas pelo pouco de conhecimento gosto de poder ajudar, eu sempre vou lendo os tutoriais e tentando para chegar na solução, assim que se consegue chegar ao objetivo..

 

Só não tenho como testar seu script :

<?php

abstract class con{


    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= DBHOST;
    protected $port; 
    protected $user= DBUSER; 
    protected $pass= DBPASS;
    protected $dbname= DBNAME;
    protected $con= NULL;





    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 = mysqli_connect( $this->host, $this->user, $this->pass);
            mysqli_select_db($this->dbname,$this->con);
            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){ 
$this->result = mysqli_query( $this->query );
$this->fetchAll();
$this->paginateLink();
$this->query .= " LIMIT $this->page, $this->perpage";
$this->pagination = false;
}
                $this->result = mysqli_query( $this->query );
            }
        }
        catch ( Exception $e )
        {
            echo $e->getMessage();
            exit;
        }
        return $this;
    }


    public function fetchAll()
    {
        $this->data = "";
        $this->rows = 0;
        while ( $row = mysqli_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 . '">«</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 . '">»</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('/\ /i',' ',$arr);
            $final = implode( ' ', $arr ) . $info;
        }
        else
        {
            $final = $str;
        }
        return $final;
    }


}


/* end file */
?>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Obrigado resolveu o problema da pagina mysql.php porem apareceu um problema na minha pagina noticias.php.

 


( ! ) Fatal error: Call to undefined method mysqli::paginate() in C:\wamp\www\sistema-noticias\news\noticias.php on line 18 Call Stack # Time Memory Function Location 1 0.0010 247280 {main}( ) ..\noticias.php:0

 

<?php
//$db->url = 'noticias.php';
$db->paginate(4); //O erro esta apontando nessa linha
$db->query("select * from noticia order by noticia_id desc")->fetchAll();
if ($db->rows >= 1):
$news = $db->data;
foreach ($news as $new):
$n = (object) $new;
$n->noticia_content_cut = $db->cut($n->noticia_content, 300, '...');
if ($n->noticia_foto == "" || strlen($n->noticia_foto) <= 1):
$n->noticia_foto = "images/nopic.png";
else :
$n->noticia_foto = "thumb.php?img=fotos/$n->noticia_foto";
endif;
?>
<div class="media">
<a class="pull-left" href="noticia.php?id=<?= $n->noticia_id ?>">
<img src="<?= $n->noticia_foto ?>" class="media-object img-polaroid" />
</a>
<div class="media-body">
<h4 class="media-heading"><?=$n->noticia_title ?></h4>
<p><small><?=$n->noticia_content_cut ?> <em><a href="noticia.php?id=<?= $n->noticia_id ?>" class="btn btn-link">leia mais</a></em></small>
</div>
</div>
<hr />
<?
endforeach;
echo $db->link;
endif;
?>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Me parece que esta faltando setar a conexão com o banco, tenta isso:

 

OBS: Mas a solução que te dei no outro script mysql realmente fez a conexão com o BD...

<php

 include_once 'mysql.php';

 ?>

Compartilhar este post


Link para o post
Compartilhar em outros sites
já está setado. Não faço a minima ideia o que pode ser.


<?php

@header( 'Content-Type: text/html; charset=iso-8859-1' );

require_once 'database/mysql.php';

$db = new Mysqli;

?>

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.