Errors trying to update mysql script to mysqli

Asked

Viewed 77 times

0

<?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" );
            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->con, $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) )
        {
            $this->data[] = $row;
        }
        if ( isset( $this->data[0] ) )
        {
            $this->rows = count( $this->data );
        }
        return $this->data;
    }

    public function rowCount()
    {
        return @mysqli_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’m developing a website and I wanted users to post the news so I didn’t have to put it straight into the code, so I had the idea to put a newsroom admin panel where the user reads on the dashboard and puts the news on the site, the scripts I found are very old and php has already discontinued mysql_ and now uses the mysqli_ since I don’t understand mysql well and I don’t intend to delve into it at the moment, I wanted your help to convert this old script to the new mysqli model so the rest I can turn around and implement on the site. I even tried several days and nothing. Someone out there who can convert it for me please :)

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){  
                    $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 */

database.conf.php

<?php
# Configuração do banco de dado 
global $databases;
$databases = array( 
    'local' => array
    (
            'host'=>'localhost',
            'port'=>3306,
            'dbname'=>'news',
            'user'=>'root',
            'password'=>''
    )
);

/* end file */

Tables.sql

-- Estrutura da tabela `noticia`
-- 

CREATE TABLE `noticia` (
  `noticia_id` int(11) NOT NULL auto_increment,
  `noticia_title` varchar(200) default NULL,
  `noticia_foto` varchar(200) default NULL,
  `noticia_content` text,
  `noticia_data` varchar(20) default NULL,
  PRIMARY KEY  (`noticia_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

-- 
-- Extraindo dados da tabela `noticia`
-- 

INSERT INTO `noticia` (`noticia_id`, `noticia_title`, `noticia_foto`, `noticia_content`, `noticia_data`) VALUES 
(2, 'Site do Evandro Moraes no AR!!!', '29a38716bd407f0c4b563f68313837d8.jpg', '<p><span style="text-align: justify;">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.<span rel="pastemarkerend" id="pastemarkerend45668"></span></span><br>\r\n\r\n</p>\r\n', '18/01/2013'),
(5, 'Et amet qui ut sint', '42e187237927e75d0c0ddf53ceaa0321.jpg', '<p><span style="text-align: justify;">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.<span rel="pastemarkerend" id="pastemarkerend88963"></span></span><br>\r\n\r\n</p>\r\n', '18/01/2013'),
(6, 'Magna nostrud dolor tempore qui', '8e5515cb741465137c4e61dae3295d42.jpg', '<p style="text-align: justify;">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.<span rel="pastemarkerend" id="pastemarkerend30919"></span><br>\r\n\r\n</p>\r\n', '18/01/2013'),
(7, 'Dolore quibusdam libero sunt rerum', '9c50a5334ba74841724f7bf66fcbe982.jpg', '<p style="text-align: justify;">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.<span rel="pastemarkerend" id="pastemarkerend23702"></span><br>\r\n\r\n</p>', '07/08/2013'),
(8, 'Magna et eiusmod dicta id', 'd25240db324fa1c2335db2b5996f76ab.jpg', '<p><span style="text-align: justify;">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.<span rel="pastemarkerend" id="pastemarkerend75618"></span></span><br>\r\n\r\n</p>\r\n', '07/08/2013');

-- --------------------------------------------------------

-- 
-- Estrutura da tabela `users`
-- 

CREATE TABLE `users` (
  `user_id` int(11) NOT NULL auto_increment,
  `user_login` varchar(20) default NULL,
  `user_password` varchar(50) default NULL,
  `user_email` varchar(200) default NULL,
  PRIMARY KEY  (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

-- 
-- Extraindo dados da tabela `users`
-- 

INSERT INTO `users` (`user_id`, `user_login`, `user_password`, `user_email`) VALUES 
(3, 'demo', '652313f76bfb278e1daaf8d3c78b7d30', '[email protected]'),
(4, 'admin', '21232f297a57a5a743894a0e4a801fc3', 'admin@admin');
  • Select the code to put here or in Pastebin

  • You did right by informing the link, but also put the script in your question, because the site asks for informed registration...

  • Ready already edited the post, I believe these are responsible for communication. Thanks for the feedback

  • You don’t need to understand mysql to do this. All native functions have in the PHP documentation, with examples, etc. It is very important to be able to do something like this, if not, you will make Sopt, forums, etc your work tool, depending on other people, time, etc... If you’ve done all this code, try changing it slowly, you can!

  • I made the modifications but no more errors, as well as does not login. It is only in the user screen and password saying that it is incorrect. I edited the Post above with the code that is now.

No answers

Browser other questions tagged

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