Mega Code Archive

 
Categories / Php / MySQL Database
 

How to load a query result into a PHP Array

<?php /* You can put this in other file and just include it */ function OpenDb($hostname,$uid,$pwd,$dbname){ $link = @mysql_pconnect($hostname,$uid,$pwd); if($link && mysql_select_db($dbname)){ return($link); } else{ return(FALSE); } } ?> <?php function QueryIntoArray($query){ settype($retval,"array"); $result= mysql_query($query); if(!$result){ print "Query Failed"; } for($i=0;$i<mysql_numrows($result);$i++){ for($j=0;$j<mysql_num_fields($result);$j++){ $retval[$i][mysql_field_name($result,$j)] = mysql_result ($result,$i,mysql_field_name($result,$j)); }//end inner loop }//end outer loop return $retval; }//end function ?> <!--An Example How To Use The functions To try it simple change the appropriate variable to your own database & tables --> <HTML> <HEAD> <TITLE>PHP Array Test</TITLE> </HEAD> <BODY BGCOLOR=WHITE> <?php OpenDb("myhost","myuid","mypwd","mydatabase") or die("Failed Opening Database"); settype($myresult,"array"); $query = "SELECT * FROM mytable"; $myresult = QueryIntoArray($query); for($i=0;$i<count($myresult);$i++){ print $myresult[$i]["MyField1"]; print $myresult[$i]["MyField2"]; } ?> </BODY> </HTML>