[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 325
  • Last Modified:

using a php class to do a database search but return an array back

Hi

I have the folling code in one of my classes. its intention is to take a SQL query and pass back an array of results for me to then use alse where, it doesnt seem to do this though, it seems to only send back 1 row?

	
public function executeQuery($query) {
				
      $db = new mysqli(_DBHOST, _DBUSER, _DBPASSWORD, _DBTABLE);
		
      if ($result = $db->query($query)) {	
	$row = $result->fetch_assoc();	
	$result->close();	
	$db->close();	
	return $row;
     }
		
}	

Open in new window



im calling it using :

$searchResultsRS = $db->executeQuery($itemSearchSql);

Open in new window



then, i wanted to pass this record (or records) to a template like this:

while ($row = mysqli_fetch_array($searchResultsRS)) {
      $items[] = array(
            'iID' => $row['iID'],
            'iCategory' => $row['iCategory'],
            'cName' => $row['cName']
                                      );
)



any ideas or tips to do this better please?
0
Neil Thompson
Asked:
Neil Thompson
  • 2
1 Solution
 
Ray PaseurCommented:
The first code snippet will only return one row.  If you want to get the entire results set, you would use an iterator like while() or maybe use PDO.  This article has parallel examples in different MySQL extensions.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

If you want, please post the rest of the class and maybe we can come up with something that will make more sense than just this function.  It's missing a lot of things it needs, like error handling.
0
 
Neil ThompsonSenior Systems DeveloperAuthor Commented:
Thanks Ray

I've fudged it to work at present as it was actually another search i needed to quickly demo.

Your tutorial is excellent so I'm now going to take a step back and have a good read and learn.

Are you aware of a good class that I can use to add/edit/delete/read from a database with all the great error handling etc build in?

Regards
Neil
0
 
Ray PaseurCommented:
Thanks for the points.  I'm not aware of any database class.  I tend to write web services (rather than web sites) and as a result of needing ultra-high performance I usually write and optimize my own code.  I'm sure there is something that offers a generalized solution - I just don't know what it is!

Best regards, ~Ray
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now