SitePoint Sponsor

User Tag List

Results 1 to 10 of 10

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Apr 2009
    Posts
    90
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Problem Creating a Class

    I am trying to convert one of my older scripts into OOP with a class but I have a question: how do I reference a variable between methods within the same class? I tried using $this->variable with no luck.

    Here's the code:

    Code:
    <?php
    
    class DisplayCat {
    
      // Insures that the value of $cat is valid
    
      public function CheckCatValue($cat)
        {
           if (($cat == "") || ($cat == "0")) 
             {
               echo "category was left blank";
             }
           elseif (is_numeric($cat) == false) 
             {
               echo "category must be a numeric value";
             }
            else 
             {
               $this->DisplayProducts($cat);	  
             }
        }
    
        // Loops through the category and displays produts
    
    	public function DisplayProducts($cat)
    	  {
                $getProducts = mysql_query("SELECT * FROM products WHERE prod_cat = $cat LIMIT $this->offset,$this->rowsperpage") or die(mysql_error());
                $num_rows = mysql_num_rows($getProducts);
    
                while($row = mysql_fetch_array( $getProducts )) 
    		  {
    		  $prod_id = $row["prod_id"];
    		  $prod_title = $row["prod_title"];
    		  $prod_pprice = $row["prod_pprice"];
    		  $prod_gprice = $row["prod_gprice"];
    		  $prod_thumb = $row["prod_thumb"];
    
    		  for ($n = 1; $n <=4; $n++) 
    		    {
    		    }
    
                echo "
    		<div class=\"catbody_block\">
    	          <div class=\"catbody_img\">
    		    <a href=\"product.php?product=$prod_id\"><img src=\"$prod_thumb\" border=\"0\" alt=\"$prod_id\" /></a>
    		  </div>
    		  <div class=\"catbody_data\">
    		    &nbsp;$prod_id | $prod_pprice <br /> &nbsp;$prod_title
    		    <br />&nbsp;<a href=\"product.php?product=$prod_id\"><img src=\"images/_info.gif\" border=\"0\" alt=\"info\"/></a><a href=\"addtocart.php?product=$prod_id\"><img src=\"images/_buy.gif\" border=\"0\" /></a>
    		  </div>
    		</div>";
    	    }
    	  }
    
      // Creates pagination values
    
      public function CreatePagination($cat,$sql,$conn) 
        {
          $sql = "SELECT COUNT(*) FROM products WHERE prod_cat = $cat";  
          $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);  
          $r = mysql_fetch_row($result);  
          $numrows = $r[0];  
    
    		if ($numrows == 0) 
    		  {
    		    echo "Numrows = 0";
    		  } 
            else 
    		  {
    		    $rowsperpage = 12;  
    			$totalpages = ceil($numrows / $rowsperpage); 
    
            if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) 
    	  {  
                 $currentpage = (int) $_GET['currentpage'];  
              } 
            else 
    	  {  
    	    $currentpage = 1;  
    	  } 
    			
            if ($currentpage > $totalpages) 
    	  {  
    	    $currentpage = $totalpages;  
    	  }  
    				 
    	if ($currentpage < 1) 
    	  {  
    	    $currentpage = 1;  
    	  }  
    				 
            $offset = ($currentpage - 1) * $rowsperpage;  
         }
      }
    
       // Displays pagination footer
    
        public function DisplayPagination($cat)
    	{
              echo "<div class=\"catbody_pagination\">More:&nbsp;";
    		
    	  if ($this->currentpage > 1) 
    	    {  
                  echo "<a href='{$_SERVER['PHP_SELF']}?$this->currentpage=1&cat=$cat'><<&nbsp;</a> ";  
    
    	      $prevpage = $this->currentpage - 1;  
            
    	    } 
    
    	  $range = 12;  
          
    	  for ($x = ($this->currentpage - $range); $x < (($this->currentpage + $range)  + 1); $x++) 
    	    {  
    		  if (($x > 0) && ($x <= $this->totalpages)) 
    		    {  
    			  if ($x == $this->currentpage) 
    			    {  
    			      echo "$x";  
    				} 
    				else
    				{  
                      echo " <a href='{$_SERVER['PHP_SELF']}?$this->currentpage=$x&cat=$cat'>$x</a> ";  
    				}
    			} 
    		}
       
    	  if ($this->currentpage != $this->totalpages) 
    	    {  
    		  $nextpage = $this->currentpage + 1;   
    		  //  echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage&cat=$cat'>></a> ";  
    		  echo " <a href='{$_SERVER['PHP_SELF']}?$this->currentpage=$this->totalpages&cat=$cat'>&nbsp;>></a>";  
    		}
    
    	  echo "&nbsp;&nbsp&nbsp;&nbsp&nbsp;&nbsp;</div>";
    	}
    }
    
    
    ?>

    Code:
    <?php
      include ("classes/displaycat.php");
      $cat = mysql_real_escape_string($_GET['cat']);
    
      $DisplayCat = new DisplayCat;
    
        $CheckCatValue = $DisplayCat->CheckCatValue($cat);
        $CreatePagination = $DisplayCat->CreatePagination($cat);
        $DisplayPagination = $DisplayCat->DisplayPagination($cat);
    		
    ?>

    I get this error:

    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

    and assume it has to do with not properly passing the values of LIMIT $offset,$rowsperpage - how do I do that?

  2. #2
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    PHP Code:
        public function DisplayProducts($cat)
          {
                
    $getProducts mysql_query("SELECT * FROM products 
    WHERE prod_cat = 
    $cat 
    LIMIT 
    $this->offset,
    $this->rowsperpage"
    ) or die(mysql_error());
                
    $num_rows mysql_num_rows($getProducts); 
    Take $this->offset - where is $this->offset set? and where is it stored so that those methods can get hold of it?

    You could have a class "property" and declare it at the top of your class like so:

    PHP Code:
    class yourclass {

    public 
    $offset 10 ;

    public function 
    DisplayProducts(){

    return 
    "offset is now " $this->offset ;

    }

    public function 
    setOffset$n ){

    $this->offset $n ;

    }


    Classes generally have properties upon which methods operate.

    PHP Code:
    $d = new yourclass ;
    $d->setOffset15 );  // optional, let default ride if you prefer
    echo $d->DisplayProducts(); 
    It is usually seen as a bad sign if your classes echo anything, they should return values, or data only - maybe have a final class which dresses up the output as html as opposed to a pdf, or a csv file
    EDIT
    Your sql is wrong because your class cannot assemble the sql statement, echo the sql statement as you work away - that will give you a better clue as to where you are going wrong.

  3. #3
    SitePoint Enthusiast
    Join Date
    Apr 2009
    Posts
    90
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    $offset is defined by the CreatePagination function like this:

    $offset = ($currentpage - 1) * $rowsperpage;

    So how do I pass that value from the CreatePagination function to the DisplayProducts function?

    I am going to remove all of the html from the DisplayProducts loop and keep them separate, sorry... I just included here while trying to wireframe and get this working.

    If I declare the variables like this:

    var $foffset = $this->offset;
    var $frowsperpage = $this->rowsperpage;

    in the class, will that work?

  4. #4
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by berliner_kindl View Post
    $offset is defined by the CreatePagination function like this:

    $offset = ($currentpage - 1) * $rowsperpage;

    So how do I pass that value from the CreatePagination function to the DisplayProducts function?
    $this->offset = ($currentpage - 1) * $rowsperpage;

    Quote Originally Posted by berliner_kindl View Post
    I am going to remove all of the html from the DisplayProducts loop and keep them separate, sorry... I just included here while trying to wireframe and get this working.

    If I declare the variables like this:

    var $foffset = $this->offset;
    var $frowsperpage = $this->rowsperpage;

    in the class, will that work?
    No.

    If you are using PHP5 you'd declare it using one of PPP (public,private,protected) not var whats more the declaration can only be a scalar value, or nothing at all.

    so

    public $offset = 10;
    OR
    public $offset ;

    offset is now available for each method to access (read) or change (write) if they want to simply by adding $this-> before it like this $this->offset.

    You'd better read up on classes, the syntax is not difficult, but if you don't put some learning time in, you'll be forever asking how they work.

    Classes get super complex super quick and before you know - all kinds of rules kick in and you lose track of what is over-writing what.

    The man is the best starting place to learn the syntax and roles and responsibilities. http://fr.php.net/manual/en/language.oop5.php

  5. #5
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    PHP Code:
    class DisplayCat {

        protected 
    $category;
        protected 
    $db;

        protected 
    $offset;
        protected 
    $currentPage;
        protected 
    $pages;
        
        public function 
    __construct($category,$db) {
        
            
    $this->category $category;
            
    $this->db $db;
            
            
    $this->_init();
        
        }
        
        protected function 
    _init() {
        
            
    $this->displayProducts();
        
        }
        
        public function 
    getOffset() {
        
            if(
    is_null($this->offset)) {
                
    $this->_createPagination();
            }
            
            return 
    $this->offset;
        
        }
        
        public function 
    getCurrentPage() {
        
            if(
    is_null($this->currentPage)) {
                
    $this->_createPagination();
            }
            
            return 
    $this->currentPage;
        
        }
        
        public function 
    getPages() {
        
            if(
    is_null($this->pages)) {
                
    $this->_createPagination();
            }
            
            return 
    $this->pages;
        
        }
        
        protected function 
    _createPagination() {
        
            
    // code to calculate offset, current page and pages
            
            
    $this->offset $offset;
            
    $this->pages $pages;
            
    $this->currentPage $currentPage
        
        
    }
        
        public function 
    displayProducts() {
        
            
    $offset $this->getOffset();
            
            
    $this->displayPagination();
        
        }
        
        public function 
    displayPagination() {
        
            
    $offset $this->getOffset();
            
    $currentPage $this->getCurrentPage();
            
    $pages $this->getPages();    
        
        }



  6. #6
    SitePoint Enthusiast
    Join Date
    Apr 2009
    Posts
    90
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    what does the underscore do?

    $this->_createPagination();

    I assume it signifies private vars like C++?

  7. #7
    play of mind Ernie1's Avatar
    Join Date
    Sep 2005
    Posts
    1,252
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by berliner_kindl View Post
    what does the underscore do?
    nothing special
    my mobile portal
    ghiris.ro

  8. #8
    SitePoint Enthusiast
    Join Date
    Apr 2009
    Posts
    90
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Cool. What about the _init function name, is there any significance to that? I cannot find anything in the manual or on google about that, but it seems like an odd name.

  9. #9
    play of mind Ernie1's Avatar
    Join Date
    Sep 2005
    Posts
    1,252
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It is the place where you can perform some application-level initialization tasks.
    It's just a naming convention.
    my mobile portal
    ghiris.ro

  10. #10
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    Using a underscore nicely distinguishes methods that are part of the public interface from those that are not. However, I don't follow this convention with properties because they are always either private or protected.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •