PHPBuilder - MySQL Field Name and Row-based Results from a Select Query



RSS Twitter
Snippets Databases

MySQL Field Name and Row-based Results from a Select Query

by: Eric Sammons
|
September 14, 2001

Version: 1.0.0

Type: Function

Category: Databases

License: GNU General Public License

Description: This functions takes an SQL statement and returns the result in an array in the following format: $Result[fieldname][row] This helps prevent having to remember the order of fields in a select query result



<?
/*
	Function Name: Perform_Select_Query
  
	Author: Eric Sammons, Vansam Software, Inc. (www.vansam.com)
	Email: eric@vansam.com

	Date: 2001-03-15
	Version 1.0.0

	Purpose:
		Receives an SQL statement (plus the database name), and returns the 
		result in an array in the following format:
			$Result[fieldname][row]

	Returns:
		If valid SQL Query, an array of the SQL Results
		If invalid Query, an error message that begins with "Error:"
		
	Sample Use:
		$SQL="Select * from tblTest";
		$SQL_Result=Perform_Select_Query($SQL, $database);
		
		if (substr($SQL_Result, 0, 5)!="Error") {
			print ($SQL_Result[fieldname][0]);
		}	
		
*/

function Perform_Select_Query ($SQL, $db) {

	$Query = mysql_db_query($db, $SQL); 	// Perform Query in MySQL
	$my_err=mysql_error();					// Check for errors
	
	// If Error, return error message
	if ($my_err) {		
		$my_err = "Error: ".$my_err;
		mysql_free_result ($Query);
		return $my_err;
	} else {
		// If no error, perform loop to populate array with fieldnames and values
		$row=0;
		$num_fields = mysql_num_fields($Query);
		// Get the field names
		for ($i=0;$i < $num_fields; $i++) {
			$fieldname[$i]=mysql_field_name($Query,$i);
		}
		// Populate the array with the appropriate values
		while ($result_array_1 = mysql_fetch_array($Query)) {
			for ($i=0;$i < $num_fields; $i++) {
				$this_fieldname = $fieldname[$i];
				$result_array[$this_fieldname][$row] = $result_array_1[$this_fieldname];
			}
			$row++;
		}
		mysql_free_result ($Query);
		return $result_array;
	}
}

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Eric Sammons

Comment:



Comment:

(Maximum characters: 1200). You have characters left.