Solved

create object oriented class to create form menu drop down select

Posted on 2013-05-17
14
601 Views
Last Modified: 2013-07-25
year is different than the other drop down select menus because it starts at 1970 and ends at this year (where selected year is the year field in the table row
array("liquor_type","varietal","bottle_region","distributor") are all id(int), name(varchar) tables

as I add different columns, this becomes complex and I have to copy paste code
is there an object oriented method of calling this code

php code
<?php
$arrFirst = array("liquor_type","varietal","bottle_region","distributor");
$arrLast = array("smith","jones","parker");

//begin bottle_year  
$column_name='bottle_year';  
$show[$column_name]='<td>';
        $show[$column_name].='<select id="'.$tablename.'" class="'.$tablename.'" name="'.$column_name.'[' . $p[$tablename.'_id'] . ']">';
    $qyear = 'SELECT '.$column_name.' FROM '.$tablename.' where '.$tablename.'_id='.$p[$tablename.'_id'].' order by '.$column_name;
    //$show[$column_name].='<br>'.$qyear;
    $ryear = $mysqli->query($qyear);
    $$tablename=0;
    while ($rowyear = $ryear->fetch_assoc()) {
         //show current table field value as 'selected' (the choice that displays default setting)
         $$tablename++;
         $current_year=date("Y");
         for ($year=1970;$year<=$current_year;$year++){
          //if ($p['bottle_year']==$rowyear['bottle_year']){
          if ($year==$rowyear[$column_name]){            
            $show[$column_name].='<option SELECTED';
          }else{
            $show[$column_name].='<option';
          }
          //echo  ' value="' . $rowyear['bottle_year'] .'">' . $rowyear['bottle_year'] . '</option>'; 
          $show[$column_name].=' value="' . $year .'">' . $year . '</option>';   
         }//end foryear
      }//end whileyear     
      if ($$tablename==0 || empty($p[$column_name])){
      $show[$column_name].='<option SELECTED value="NULL">No Choice</option>';
      }else{
      //echo  '<option value="NULL">No Choice</option>';  
      }
    
      
    $show[$column_name].='</select><br>';         
    //}else{ 
   // }
   //echo  '<br>for '.$tablename.' number of choices are: '.$$tablename;
 
$show[$column_name].='</td>';  
//end bottle_year




foreach($arrFirst as $index => $column_name)
{
  //echo "First Name = $column_name";
  //echo "Last Name = " . $arrLast[$index];
//begin multiselect
//$column_name='bottle_year';  
$show[$column_name]='<td>';
//$show[$column_name].=$column_name.' '.$arrLast[$index];
        $show[$column_name].='<select id="'.$tablename.'" class="'.$tablename.'" name="'.$column_name.'[' . $p[$tablename.'_id'] . ']">';
    $qyear = 'SELECT '.$column_name.'_id, '.$column_name.'_name FROM '.$column_name.' order by '.$column_name.'_name';
    //$show[$column_name].='<br>'.$qyear;
    $ryear = $mysqli->query($qyear);
    $$tablename=0;
    while ($rowyear = $ryear->fetch_assoc()) {
         //show current table field value as 'selected' (the choice that displays default setting)
         $$tablename++;
         //$current_year=date("Y");
         //for ($year=1970;$year<=$current_year;$year++){
          if ($p[$column_name]==$rowyear[$column_name.'_id']){
          //if ($year==$rowyear[$column_name]){            
            $show[$column_name].='<option SELECTED';
          }else{
            $show[$column_name].='<option';
          }
          $show[$column_name].=' value="' . $rowyear[$column_name.'_id'] .'">' . $rowyear[$column_name.'_name'] . '</option>'; 
         // echo  ' value="' . $year .'">' . $year . '</option>';   
        // }//end foryear
      }//end whileyear     
      if ($$tablename==0 || empty($p[$column_name])){
      $show[$column_name].='<option SELECTED value="NULL">No Choice</option>';
      }else{
      //echo  '<option value="NULL">No Choice</option>';  
      }
    
      
    $show[$column_name].='</select><br>';         
    //}else{ 
   // }
   //echo  '<br>for '.$tablename.' number of choices are: '.$$tablename;
 
$show[$column_name].='</td>';  
//end multiselect
}//end foreach loop through columns
  
?>

Open in new window




some html output
<select id="wine" class="wine" name="liquor_type[5]"><option value="1">red</option><option value="4">rose</option><option value="3">sparkling</option><option value="6">tequila</option><option value="5">vodka</option><option value="7">whisky</option><option value="2">white</option><option SELECTED value="NULL">No Choice</option></select>

Open in new window

0
Comment
Question by:rgb192
  • 8
  • 6
14 Comments
 
LVL 34

Accepted Solution

by:
gr8gonzo earned 500 total points
ID: 39176017
Something like this?

$show[$column_name] .= '<td>'.DBDropDown::Quick($mysqli,"wine","liquor_type",$p).'</td>';
$show[$column_name] .= '<td>'.DBDropDown::Quick($mysqli,"wine","varietal",$p).'</td>';

class DBDropDown
{
	private $table = "";
	private $column = "";
	private $p = null; // Not sure what this is - some kind of lookup table...?
	private $options = array();
	
	public static function Quick($link,$table,$column,$p)
	{
		$tmpDDD = new DBDropDown($link,$table,$column,$p);
		return $tmpDDD->render();
	}
	
	public function __construct($link,$table,$column,$p)
	{
		// Store parameters for later...
		$this->table = $table;
		$this->column = $column;
		$this->p = $p;
		
		// Perform query
		$query = 'SELECT '.$column.' FROM '.$table.' where '.$table.'_id='.$p[$table.'_id'].' order by '.$column;
		$results = $link->query($query);
		
		// Loop through results and add options
		while($row = $results->fetch_assoc())
		{
			for ($year = 1970; $year <= date("Y"); $year++)
			{
				$this->addOption($year, $year, ($year == $row[$column]));
			}
		}
		
		// When there's no option...
		if(($results->num_rows == 0) || empty($p[$column]))
		{
			$this->addOption("No Choice","NULL",true);
		}
	}
	
	public function addOption($text,$value,$selected)
	{
		$this->options[] = array("text" => $text,"value" => $value, "selected" => $selected);
	}
	
	public function render()
	{
		$selectID = $this->table;
		$selectClass = $this->table;
		$selectName = $this->column . "[". $this->p[$this->table.'_id'] . "]";
		
		// Build the HTML
		$html = "<select id='{$selectID}' class='{$selectClass}' name='{$selectName}'>";
		foreach($this->options as $option)
		{
			$html .= "<option value='".$option["value"]."' ".($option["selected"] ? "selected" : "").">".$option["text"]."</option>";
		}
		$html .= "</select><br />";
		
		return $html;
	}
}

Open in new window

0
 

Author Comment

by:rgb192
ID: 39176239
>>private $p = null; // Not sure what this is - some kind of lookup table...?
is this a lookup table?
$tablename is a table that is id int, name varchar that corresponds to the main wine table
table:
bottle_type
bottle_type_id int auto_increment primary key
bottle_type_name varchar

$q = "SELECT * from $tablename";    
$r = $mysqli->query($q); // Run the query.          
while ($p = $r->fetch_assoc()) {
}



for loop 1970-2013 is only if column is wine_year
    // Loop through results and add options
    while($row = $results->fetch_assoc())
    {
      for ($year = 1970; $year <= date("Y"); $year++)
      {
        $this->addOption($year, $year, ($year == $row[$column]));
      }
    }

Open in new window



other columns use rows of select option from the mysql table
        $show[$column_name].='<select id="'.$tablename.'" class="'.$tablename.'" name="'.$column_name.'[' . $p[$tablename.'_id'] . ']">';
    $qyear = 'SELECT '.$column_name.'_id, '.$column_name.'_name FROM '.$column_name.' order by '.$column_name.'_name';
    //$show[$column_name].='<br>'.$qyear;
    $ryear = $mysqli->query($qyear);
    $$tablename=0;
    while ($rowyear = $ryear->fetch_assoc()) {
         //show current table field value as 'selected' (the choice that displays default setting)
         $$tablename++;
         //$current_year=date("Y");
         //for ($year=1970;$year<=$current_year;$year++){
          if ($p[$column_name]==$rowyear[$column_name.'_id']){
          //if ($year==$rowyear[$column_name]){            
            $show[$column_name].='<option SELECTED';
          }else{
            $show[$column_name].='<option';
          }
          $show[$column_name].=' value="' . $rowyear[$column_name.'_id'] .'">' . $rowyear[$column_name.'_name'] . '</option>'; 
         // echo  ' value="' . $year .'">' . $year . '</option>';   
        // }//end foryear
      }//end whileyear     

Open in new window

0
 

Author Comment

by:rgb192
ID: 39203041
Fatal error: Call to a member function query() on a non-object in C:\Users\Acer\Documents\NuSphere PhpED\Projects\gonzo-oo-dropdown.php on line 27
0
 
LVL 34

Expert Comment

by:gr8gonzo
ID: 39204464
Can you show me what that code looks like?

In your original code, you had this:
$ryear = $mysqli->query($qyear);

...so I assumed $mysqli was a database link / object. In my code that I provided, it should be passed in:

DBDropDown::Quick($mysqli, ....)
--> function Quick($link,...)
      --> new DBDropDown($link,...)
            --> function __construct($link, ...)
                  --> $results = $link->query($query);

So my assumption is that $mysqli isn't a database link in the code you have...
0
 

Author Comment

by:rgb192
ID: 39241590
$mysqli is a link to the database

I do not understand the difference

$ryear = $mysqli->query($qyear);
 and
$results = $link->query($query);
0
 
LVL 34

Expert Comment

by:gr8gonzo
ID: 39244273
There should not be a difference as long as you pass in a valid database link. Outside of the class, you are calling the database link $mysqli. When you make the call to "Quick", you are passing in the link. The class simply assigns its own name for the variable.

Take the following example:

$mary = new Human("Mary Smith");
$john = new Human("John Smith");

ThingsThatHumansDo::SayHello($mary);
ThingsThatHumansDo::SayHello($john);


class Human
{
  public $name = "";
  public function __construct($name)
  {
    $this->name = $name;
  }
}

class ThingsThatHumansDo
{
	public static function SayHello($human)
	{
		echo $human->name . " says hello!";
	}	
}

Open in new window


Outside of the class, you have variables named $mary and $john, while INSIDE the class, you have a more generic name of $human.

In your scenario, outside the class, you have $mysqli, and inside the class you have $link. They should be the same database link, but the system is complaining that it's not a valid link.

So that usually means that OUTSIDE the class, $mysqli is not a valid database link (at least not in C:\Users\Acer\Documents\NuSphere PhpED\Projects\gonzo-oo-dropdown.php).

If you show me the full source of that script, I can probably show you what's happening, but I'm guessing that you don't have the database connection happening at the top of your gonzo-oo-dropdown.php script.
0
 

Author Comment

by:rgb192
ID: 39270464
I moved the code to wamp

<?php
ini_set("display_errors", true);
include('mysqli_connect.php');
$show[$column_name] .= '<td>'.DBDropDown::Quick($mysqli,"wine","liquor_type",$p).'</td>';
$show[$column_name] .= '<td>'.DBDropDown::Quick($mysqli,"wine","varietal",$p).'</td>';

class DBDropDown
{
  private $table = "";
  private $column = "";
  private $p = null; // Not sure what this is - some kind of lookup table...?
  private $options = array();
  
  public static function Quick($link,$table,$column,$p)
  {
    $tmpDDD = new DBDropDown($link,$table,$column,$p);
    return $tmpDDD->render();
  }
  
  public function __construct($link,$table,$column,$p)
  {
    // Store parameters for later...
    $this->table = $table;
    $this->column = $column;
    $this->p = $p;
    
    // Perform query
    $query = 'SELECT '.$column.' FROM '.$table.' where '.$table.'_id='.$p[$table.'_id'].' order by '.$column;
    $results = $link->query($query);
    
    // Loop through results and add options
    while($row = $results->fetch_assoc())
    {
      for ($year = 1970; $year <= date("Y"); $year++)
      {
        $this->addOption($year, $year, ($year == $row[$column]));
      }
    }
    
    // When there's no option...
    if(($results->num_rows == 0) || empty($p[$column]))
    {
      $this->addOption("No Choice","NULL",true);
    }
  }
  
  public function addOption($text,$value,$selected)
  {
    $this->options[] = array("text" => $text,"value" => $value, "selected" => $selected);
  }
  
  public function render()
  {
    $selectID = $this->table;
    $selectClass = $this->table;
    $selectName = $this->column . "[". $this->p[$this->table.'_id'] . "]";
    
    // Build the HTML
    $html = "<select id='{$selectID}' class='{$selectClass}' name='{$selectName}'>";
    foreach($this->options as $option)
    {
      $html .= "<option value='".$option["value"]."' ".($option["selected"] ? "selected" : "").">".$option["text"]."</option>";
    }
    $html .= "</select><br />";
    
    return $html;
  }
}

Open in new window


( ! ) SCREAM: Error suppression ignored for
( ! ) Notice: Undefined variable: p in C:\wamp\www\gonzo\gonzo-oo-dropdown2.php on line 4
Call Stack
#	Time	Memory	Function	Location
1	0.0394	702392	{main}( )	..\gonzo-oo-dropdown2.php:0

( ! ) SCREAM: Error suppression ignored for
( ! ) Fatal error: Call to a member function fetch_assoc() on a non-object in C:\wamp\www\gonzo\gonzo-oo-dropdown2.php on line 32
Call Stack
#	Time	Memory	Function	Location
1	0.0394	702392	{main}( )	..\gonzo-oo-dropdown2.php:0
2	0.4482	722808	DBDropDown::Quick( )	..\gonzo-oo-dropdown2.php:4
3	0.4483	723464	DBDropDown->__construct( )	..\gonzo-oo-dropdown2.php:16

Open in new window

0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 34

Expert Comment

by:gr8gonzo
ID: 39272085
I think the problem is this:
include('mysqli_connect.php');

I don't think that code is running properly in your script. If mysqli_connect.php is not inside C:\wamp\www\gonzo, then you'll need to have the mysqli_connect path specified in the include_path directive in php.ini:

Example:
include_path = ".;c:\wamp\www"
0
 

Author Comment

by:rgb192
ID: 39273651
mysqli_connect.php is in c:\wamp\gonzo\
0
 
LVL 34

Expert Comment

by:gr8gonzo
ID: 39274371
1. Your code mentions "www" but you just said "C:\wamp\gonzo" without the "www" - are there two gonzo folders?

2. Try changing the code from "include" to "require"

3. Inside mysqli_connect.php, make sure there are no other problems or failed dependencies. Everything indicates that mysqli_connect.php should create the database connection variable called $mysqli but the error indicates that it is not. So it seems like something in mysqli_connect is not working correctly.
0
 

Author Comment

by:rgb192
ID: 39274899
<?php # Script 16.4 - mysqli_connect.php

// This file contains the database access information. 
// This file also establishes a connection to MySQL 
// and selects the database.

// Set the database access information as constants:
DEFINE ('DB_USER', 'user');
DEFINE ('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'remotehost');
//DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'dbname');


// Make the connection:
$dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

if (!$dbc) {
	trigger_error ('Could not connect to MySQL: ' . mysqli_connect_error() );
  echo "not connected";
}else{
//echo "connected";
}
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
?>

Open in new window



changed include to require and can not find 'www'
<?php
ini_set("display_errors", true);
require('mysqli_connect.php');
$show[$column_name] .= '<td>'.DBDropDown::Quick($mysqli,"wine","liquor_type",$p).'</td>';
$show[$column_name] .= '<td>'.DBDropDown::Quick($mysqli,"wine","varietal",$p).'</td>';

class DBDropDown
{
  private $table = "";
  private $column = "";
  private $p = null; // Not sure what this is - some kind of lookup table...?
  private $options = array();
  
  public static function Quick($link,$table,$column,$p)
  {
    $tmpDDD = new DBDropDown($link,$table,$column,$p);
    return $tmpDDD->render();
  }
  
  public function __construct($link,$table,$column,$p)
  {
    // Store parameters for later...
    $this->table = $table;
    $this->column = $column;
    $this->p = $p;
    
    // Perform query
    $query = 'SELECT '.$column.' FROM '.$table.' where '.$table.'_id='.$p[$table.'_id'].' order by '.$column;
    $results = $link->query($query);
    
    // Loop through results and add options
    while($row = $results->fetch_assoc())
    {
      for ($year = 1970; $year <= date("Y"); $year++)
      {
        $this->addOption($year, $year, ($year == $row[$column]));
      }
    }
    
    // When there's no option...
    if(($results->num_rows == 0) || empty($p[$column]))
    {
      $this->addOption("No Choice","NULL",true);
    }
  }
  
  public function addOption($text,$value,$selected)
  {
    $this->options[] = array("text" => $text,"value" => $value, "selected" => $selected);
  }
  
  public function render()
  {
    $selectID = $this->table;
    $selectClass = $this->table;
    $selectName = $this->column . "[". $this->p[$this->table.'_id'] . "]";
    
    // Build the HTML
    $html = "<select id='{$selectID}' class='{$selectClass}' name='{$selectName}'>";
    foreach($this->options as $option)
    {
      $html .= "<option value='".$option["value"]."' ".($option["selected"] ? "selected" : "").">".$option["text"]."</option>";
    }
    $html .= "</select><br />";
    
    return $html;
  }
}

Open in new window

0
 
LVL 34

Expert Comment

by:gr8gonzo
ID: 39275298
Okay, so the script is not including the mysqli_connect.php file because it can't find it. Make sure the mysqli_connect.php is in the same folder as the script.
0
 

Author Comment

by:rgb192
ID: 39304731
mysqli_connect.php is in the same folder

Fatal error: Call to a member function fetch_assoc() on a non-object in C:\wamp\www\gonzo\gonzo-oo-dropdown2.php on line 32
0
 

Author Closing Comment

by:rgb192
ID: 39356102
I did not fully understand this answer, but I thought that it followed all the steps I need to learn to create an object oriented class.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now