8 Replies - 1992 Views - Last Post: 12 November 2009 - 06:45 AM Rate Topic: ***** 1 Votes

#1 Shiznit  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 67
  • Joined: 14-September 07

OOP - Displaying Query Results

Posted 11 November 2009 - 09:27 PM

So I've finally decided to take that plunge and try to broaden my PHP knowledge by developing part of a personal project using OOP...I'm trying to do it all piece by piece so I can really learn and understand what I'm doing. If my function is too simple or whatever, I'm ok with that. I don't want to get to crazy with this particular function to the point where I can't understand what its original purpose was.

I've created a function:
  public function showProjects($sort) {
	$project_list_result = mysql_query("SELECT * FROM projects ORDER BY name ".$sort."") or die ('Project list could not be generated: '.mysql_error());
		
	return $project_list_result;
  }



The function is part of a class (Projects) that is included in the page that is going to display these records

When I try to use a while loop, my computer goes into overdrive and will eventually either display a white page, or it will display the name of the first project in the list 80 bajillion times:


 $project_list = new Projects();
 while ($project_list_row = mysql_fetch_assoc($project_list->showProjects($sort))) { // The $sort variable is set much earlier in the page - it is not a typo from the function
	  $page->contentSet('
		<tr>
			<td>'.$project_list_row['name'].'</td>
			<td>'.$project_list_row['url'].'</td>
			<td>'.$project_list_row['added'].'</td>
			<td valign="middle" align="center"><img src="images/edit.png" /></td>
			<td valign="middle" align="center"><img src="images/delete.png" /></td>
		</tr>
	');

 }


I have done many googles trying to find anything similar to what I'm doing and have been presented mostly with pagination class/function tutorials. While these tutorials aren't useless (I will have to implement them one day I would guess), I cannot follow what it is they are trying to do and wind up lost within the first 10-15 lines of code. I've also searched around on PHP.net and couldn't find any help there (my guess is because I didn't really know what to look for).

Some of my googling has shown me that instead of using a while loop, I should actually be using a foreach or a while-list. It is almost about this point in the code that I begin to get lost.

I know that there are 13 records in the table I'm querying.

Any help is greatly appreciated and please keep in mind that because I've been writing procedural code for so long, all of this oop stuff is difficult for me to wrap my head around :(

Thanks!

This post has been edited by Shiznit: 11 November 2009 - 09:28 PM


Is This A Good Question/Topic? 0
  • +

Replies To: OOP - Displaying Query Results

#2 noorahmad  Icon User is offline

  • Untitled
  • member icon

Reputation: 209
  • View blog
  • Posts: 2,290
  • Joined: 12-March 09

Re: OOP - Displaying Query Results

Posted 11 November 2009 - 09:57 PM

Here is a piece of my class
function getResult($strQuery){
		$query = mysql_query($strQuery)or die(mysql_error());		
		if(mysql_num_rows($query)>0){
			$result = array();
			while($fetch = mysql_fetch_assoc($query)){
				$result[] = $fetch;
			}
			return $result;		
		}else{
			return false;
		}
	}


and how to use it
$obj = new DBClass();
$result = $obj->getResult("SELECT * FROM users");
if(!$result == false){
echo "<pre>".print_r($result,true)."</pre>";
}


:)
Was This Post Helpful? 0
  • +
  • -

#3 Shiznit  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 67
  • Joined: 14-September 07

Re: OOP - Displaying Query Results

Posted 11 November 2009 - 11:11 PM

First, thank you for the quick reply! :)

and now the frustration sets in :(

I copied and pasted your snippet, with a change only to the class name and table name. Lo and behold! It displayed an array, as would be expected. After struggling with my chronic ffs (fat finger syndrome), I was finally able to rewrite my function and page code:

public function showProjects($query) {
		$project_list_result = mysql_query($query) or die ('Project list could not be generated: '.mysql_error());
		
		if (mysql_num_rows($project_list_result) > 0) {
			$result = array();
			
			while ($fetch = mysql_fetch_assoc($project_list_result)) {
				$result[] = $fetch;
			}
			
			return $result;
		}
		
		else {
			return false;
		}
	}

$project_list = new Projects();
$result = $project_list->showProjects("SELECT * FROM projects ORDER BY name ".$sort."");
if(!$result == false){

	foreach ($result AS $project) {
		$page->contentSet('
			<tr>
				<td>'.$project['name'].'</td>
				<td>'.$project['url'].'</td>
				<td>'.$project['added'].'</td>
				<td align="center" valign="middle"><img src="images/edit.png" /></td>
				<td align="center" valign="middle"><img src="images/delete.png" /></td>
			</tr>
		
		');
	}
}


It all works perfectly now!

I have never understood arrays. You know how that goes - use them all the time, but never fully understand when or how to create one. And that is, I think, the only part of your "if (mysql_num_rows($project_list_result) > 0)" that I don't understand. Would you be able to explain this for me?

I also noticed that you took the "SELECT" statement out of the function as well. I know in a previous post that I had, a responder had also moved the query from the function back to the page. When I had written the query into the function it was because that's a query that's never going to change, other than the $sort. In different books and different tutorials I've seen it done either way. I guess my question is whether or not it is better practice to keep the statement within the page code, or is it a preference, or is it a case-by-case kinda thing?

You were truly a big help for me this evening. I have 2 more functions that I want to get in place and then I think this section of my admin will be complete :)

Thanks again, and I look forward to hearing about what the array means and whether or not it's appropriate to put a query statement in a function.
Was This Post Helpful? 0
  • +
  • -

#4 noorahmad  Icon User is offline

  • Untitled
  • member icon

Reputation: 209
  • View blog
  • Posts: 2,290
  • Joined: 12-March 09

Re: OOP - Displaying Query Results

Posted 11 November 2009 - 11:34 PM

array
Array definition from official PHP site:

Quote

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.


you mean this piece of code $result = $obj->getResult("SELECT * FROM users"); if you put the query in a variable $strQuery ="SELECT * FROM users"; and then using it in your function $result = $obj->getResult($strQuery); both are the same but putting it in a variable is a good practice, sometimes you need to see you query and then you should save it a variable.

and I used echo "<pre>".print_r($result,true)."</pre>"; for testing purpose not for printing the data in page.

Quote

but never fully understand when or how to create one

OK I want to play with countries name in page so what I need to store all counties name in an array something like this:
$countries = array("USA","UAE","RUSSIA","INDIA");
foreach($countries as $country){
	echo $country;
}


and lets say that you are getting Users name from database then you print it in page, what you should to do store all names in a variable and then print it using loops :)

:)


and let me know if you need more information
Was This Post Helpful? 1
  • +
  • -

#5 Shiznit  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 67
  • Joined: 14-September 07

Re: OOP - Displaying Query Results

Posted 11 November 2009 - 11:51 PM

View Postnoorahmad, on 11 Nov, 2009 - 10:34 PM, said:

you mean this piece of code $result = $obj->getResult("SELECT * FROM users"); if you put the query in a variable $strQuery ="SELECT * FROM users"; and then using it in your function $result = $obj->getResult($strQuery); both are the same but putting it in a variable is a good practice, sometimes you need to see you query and then you should save it a variable.


Yes, that was the line to which I was referring. Thank you for clarifying why you did that and I will keep it in mind when I start to work on my delete function ;)

View Postnoorahmad, on 11 Nov, 2009 - 10:34 PM, said:

and I used echo "<pre>".print_r($result,true)."</pre>"; for testing purpose not for printing the data in page.


I use <pre>'s all the time - in this case, it helped me to realize that my ffs was in full-swing ;)

View Postnoorahmad, on 11 Nov, 2009 - 10:34 PM, said:

$countries = array("USA","UAE","RUSSIA","INDIA");
foreach($countries as $country){
	echo $country;
}


That part I do understand. As a matter of fact, just recently a form I'd created needed to have select's for a date and I did exactly what you demonstrated.

I think my question is more about $result = array() - if $result[] = $fetch, why is $result = array() necessary? Doesn't $result[] already mean that the value of $fetch is going to be arrayed?
Was This Post Helpful? 0
  • +
  • -

#6 noorahmad  Icon User is offline

  • Untitled
  • member icon

Reputation: 209
  • View blog
  • Posts: 2,290
  • Joined: 12-March 09

Re: OOP - Displaying Query Results

Posted 12 November 2009 - 12:10 AM

Quote

I think my question is more about $result = array() - if $result[] = $fetch, why is $result = array() necessary? Doesn't $result[] already mean that the value of $fetch is going to be arrayed?

It is generally better to declare variable before using it :)

lets say I want to store countries in a $str variable which didn't declared before using it.
$countries = array("USA","UAE","RUSSIA","INDIA");
foreach($countries as $country){
        $str .= $country;
}
echo $str;

what will happens, it will store all values in variable but it gives the error Notice: Undefined variable: str in D:\wamp\www\..., why because variable is not declared for the first time and PHP variables are auto-declared, and if we declare $str before loop it not show any error
Hope it helps :)

This post has been edited by noorahmad: 12 November 2009 - 12:23 AM

Was This Post Helpful? 1
  • +
  • -

#7 Shiznit  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 67
  • Joined: 14-September 07

Re: OOP - Displaying Query Results

Posted 12 November 2009 - 12:50 AM

I wish I could remember where I'd seen your explanation before. I know it was years ago, but as soon as I saw what you posted it was so much clearer.

It should be very bright where you are right now as one helluva lightbulb has lit up here!

Thank you so very much for your help tonight. I know I'm still going to encounter more issues, but at least I'm not feeling entirely stupid anymore.
Was This Post Helpful? 0
  • +
  • -

#8 noorahmad  Icon User is offline

  • Untitled
  • member icon

Reputation: 209
  • View blog
  • Posts: 2,290
  • Joined: 12-March 09

Re: OOP - Displaying Query Results

Posted 12 November 2009 - 01:00 AM

You are welcome :)
Was This Post Helpful? 0
  • +
  • -

#9 CTphpnwb  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3030
  • View blog
  • Posts: 10,556
  • Joined: 08-August 08

Re: OOP - Displaying Query Results

Posted 12 November 2009 - 06:45 AM

If you want to use OOP, use it to simplify your code since that's what it's for! The code below breaks things up into class methods which do the work of reading from the database (missing the connect functions which I assume you have), outputting the html, and the decision making logic in the controlling code. This should be easier to edit because it has a structure that can easily be followed.

IT IS UNTESTED!
<?php
class Projects {

	var $query_results = array();
	var $html_output;

	public function showProjects($query) {
		$project_list_result = mysql_query($query) or die ('Project list could not be generated: '.mysql_error());
		
		if (mysql_num_rows($project_list_result) > 0) {
			$result = array();
			
			while ($fetch = mysql_fetch_assoc($project_list_result)) {
			$result[] = $fetch;
			}
			
			return $result;
		}
		
		else {
			return false;
		}
	}

	public function showResults() {
		foreach ($this->query_results AS $project) {
			$this->contentSet('
				<tr>
					<td>'.$project['name'].'</td>
					<td>'.$project['url'].'</td>
					<td>'.$project['added'].'</td>
					<td align="center" valign="middle"><img src="images/edit.png" /></td>
					<td align="center" valign="middle"><img src="images/delete.png" /></td>
				</tr>
			
			');
		}
	}

	public function contentSet($newcontent) {
		$this->html_output .= $newcontent; // Or what ever you're doing to set content!
	}
} // End class definition

// Begin controlling code
$sort = "Some Name";

$project_list = new Projects();
$project_list->showProjects("SELECT * FROM projects ORDER BY name ".$sort."");
if(count($project_list->query_results > 0 ){
	$project_list->showResults() 
}


?>

This post has been edited by CTphpnwb: 12 November 2009 - 06:47 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1