Hi I am trying to store MySQL result into a global array
class db
{
function CustomLoad($table_name,$Fields)
{
global $_MYSQL_DATA;
$_MYSQL_DATA=array();
$qry = mysql_query("SELECT * FROM $table_name") or die(mysql_error());
while($row = mysql_fetch_assoc($qry))
{
foreach($Fields as $r=>$key)
{
$_MYSQL_DATA[$r] = $row[$r];
}
}
}
}
I am calling like this
$dbObj = new db();
$fields = array("FIELD_1"=>"FIELD 1","FIELD_2"=>"FIELD 2","FIELD_3"=>"FIELD 3","FIELD_4"=>"FIELD 4");
$dbObj->CustomLoad("registrations",$fields);
print_r($_MYSQL_DATA);
The problem is I am getting the last result only. like Array ( [FIELD_1] => A [FIELD_2] => B [FIELD_3] => C [FIELD_4]=> D )
Just use the following:
$_MYSQL_DATA = array(); // you should declare your variables, even if it's not mandatory
while($row = mysql_fetch_assoc($qry)) // USE PDO or MySQLi !!!!!
{
$_MYSQL_DATA[] = $row;
}
Note
The []
operator generates the smallest, positive, numeric key that is not used in your array.
Examples:
$array = array(0 => 'b', 1 => 'a');
$array[] = 'c'; // will place it in $array[2]
$array = array();
$array[] = 'a'; // will place in $array[0]
And now ... the rant about PDO / MySQLi (because I have to say it :P).
MySQL is officially deprecated since PHP 5.5, and it will no longer be maintained. You should consider porting your code to either MySQLi or PDO.
in foreach there should be $row not $Field. Also run a counter
$i=0;
while($row = mysql_fetch_assoc($qry))
{
foreach($row as $r=>$key)
{
$_MYSQL_DATA[$i][$r] = $key;
}
$i++;
}