Jump to content

Recommended Posts

Well hello studies?, Well I'm new to PHP was putting into practice what you learned during the school days and I'm having errors like these 
can someone give me a sense of where I'm going wrong please?
 
 
Notice  and error the ref.php
 
Notice: Undefined index: id in C:\xampp\htdocs\ref.php on line 21
Notice: Undefined variable: n in C:\xampp\htdocs\ref.php on line 38 Notice: Trying to get property of non-object in C:\xampp\htdocs\ref.php on line 38

Notice: Undefined variable: n in C:\xampp\htdocs\ref.php on line 39

Notice: Trying to get property of non-object in C:\xampp\htdocs\ref.php on line 39

Notice: Undefined variable: n in C:\xampp\htdocs\ref.php on line 45

Notice: Trying to get property of non-object in C:\xampp\htdocs\ref.php on line 45

<?php
@header( 'Content-Type: text/html; charset=iso-8859-1' );
require_once 'database/mysql.php';
$db = new Mysql;
?>
<!DOCTYPE html>
	<html>
	<head>
		 <title>News</title>	
		 <link href="css/home.css" type="text/css" rel="stylesheet">
		 <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
		 <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>
	</head>
	<body>
		<div id="news" class="span12">				
			<?php			
			$db = new Mysql;
			$nid_noticia = $_GET['id'];
			$db->query("select * from noticia where noticia_id = $nid_noticia")->fetchAll();
			if ($db->rows >= 1):
				$n = (object) $db->data[0];
				$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 = "fotos/$n->noticia_foto";
				endif;
			endif;
			?>
			<div class="media">
				<a  class="pull-left">
					<img src="<?= $n->noticia_foto ?>" class="media-object img-polaroid" />
				</a>
				<div class="media-body">
					<h4 class="media-heading"><?=$n->noticia_title ?></h4>
					<p><?=$n->noticia_content ?></p>
				</div>
			</div>			
			<ul class="pager">
			  <li class="previous"><a href="javascript:history.back()">← Voltar</a></li>
			  <?php
				 $next_id = $n->noticia_id; 
				 $db->query("select * from noticia where noticia_id > $next_id order by noticia_id asc")->fetchAll();
				 if($db->rows >= 1):
				 $next_id = $db->data[0]['noticia_id'];
			  ?>
			  <?php endif; ?>
			</ul>			
		</div>
    </body>
</html>

Error the mysql.php

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\database\mysql.php on line 98

<?php

/* autor: Rafael Clares <rafadinix@gmail.com> */

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" ) or die ("Não foi possível conectar: " . mysql_error());
            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 ) ) // LINE 98 <<<<<<<<<<<
        {
            $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 */
?>

 

 

Link to comment
https://forums.phpfreaks.com/topic/291063-notice-warning-is-more/
Share on other sites

the mysql_fetch_array() expects parameter 1 to be resource, boolean given error is very common. you can search the web to find out what it means and how to find what is causing it.

 

however, the mysql_ (no i) database functions are obsolete, depreciated, and will be removed in an future php release. you should not be wasting any time writing code using the msyql_ functions. you should instead be using either the mysqli_ (with an i) or PDO database libraries.

Most of your un-defined variables come from the failed query.  There is one variable that may be causing the failed variable, because it is un-defined.

undefined index: id

 

$nid_noticia = $_GET['id'];

 

So to make sure we get a value for this, we must set a default value:

 

$nid_noticia = empty( $_GET['id']) ? 1 : (int)$_GET['id'];  //id should always be an integer, so cast it to the type:

 

Also, forget that you have ever learned error suppression.  Really, forget it.  Just fix the errors, and you will have very little need of it:

Don't do it:

@header();

 

Other things worth mentioning.
1. What Mac_Gyver said.

2. Pagination should not be in the database class. I keep this as a class of it's own.

3. Neither should the database class determine what the URL is.
 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.