Store MySQL result in associative array - php

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++;
}

Related

PHP loop to read from SQLite and write to arrays/JSON

I have a SQLite3 database which contains 4 tables with 9 rows each.
I've tried to do each one of the arrays one-by-one, with basically the same code as below (everything in the foreach loop), and it worked fine. I guess I just made some stupid mistakes (I don't really use PHP, this is pretty much the only project I've used it in). I tried to fix it, but somehow PHP is not really friendly today.
Currently the code below returns a JSON with 4 empty arrays.
<?php
header('Content-type: application/json');
$db = new PDO('sqlite:whad.db')or die('Could not open database');
$arDaniel = array();
$arAndi = array();
$arDave = array();
$arSimon = array();
for ($j=0; $j < 4; $j++) {
$name;
$arr;
if (j == 0) {
$name = 'Daniel';
$arr = $arDaniel;
}
elseif (j == 1) {
$name = 'Andi';
$arr = $arAndi;
}
elseif (j == 2) {
$name = 'Dave';
$arr = $arDave;
}
elseif (j == 3) {
$name = 'Simon';
$arr = $arSimon;
}
$query = "SELECT Datum, ID, RR, RL, KB, BD, SD, KH, Reihenfolge FROM $name ORDER BY date(Datum)";
$i = 1;
foreach($res = $db->query($query) as $value) {
$curr = array();
array_push($curr["Datum"] = $value[0]);
array_push($curr["ID"] = $value[1]);
array_push($curr["RR"] = $value[2]);
array_push($curr["RL"] = $value[3]);
array_push($curr["KB"] = $value[4]);
array_push($curr["BD"] = $value[5]);
array_push($curr["SD"] = $value[6]);
array_push($curr["KH"] = $value[7]);
array_push($curr["Reihenfolge"] = $value[8]);
array_push($arr[$i] = $curr);
$i++;
}
}
$json = array(
"Daniel" => $arDaniel,
"Andi" => $arAndi,
"Dave" => $arDave,
"Simon" => $arSimon
);
echo json_encode($json);
$db = NULL;
?>
EDIT: Removed quotes around $curr.
You have many unnecassary variables with the same data.
You simply could do the following
<?php
header('Content-type: application/json');
$db = new PDO('sqlite:whad.db')or die('Could not open database');
$json = array(
"Daniel" => array(),
"Andi" => array(),
"Dave" => array(),
"Simon" => array()
);
foreach($json as $name => &$arr){
$query = "SELECT Datum, ID, RR, RL, KB, BD, SD, KH, Reihenfolge FROM $name ORDER BY date(Datum)";
$stmt = $db->query($query);
//now comes the trick, that you tell pdo to fecth them already as array
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
unset($arr);
echo json_encode($json);
?>
Look at the first example here: http://php.net/manual/de/pdostatement.fetchall.php
Also note the & before $arr, which will handle the $arr variable as reference (also the unset, because after the last pass, it would still be set, this is just good style to clean up)
Update:
As in the other answer you have to use PDO::FETCH_ASSOC to get an array with only the index names.
There are more than one error in your code:
$arDaniel = array();
$arAndi = array();
$arDave = array();
$arSimon = array();
for ($j=0; $j < 4; $j++) {
$name; # <---
$arr; # <---
This sort of ‘declaration’ in php is unnecessary, you can remove $name and $arr (it's not an error, btw);
if (j == 0) { # <---
In the for loop you use $j, you can't use j here: replace it with $j (in php variables are ever prepended by $);
$name = 'Daniel';
$arr = $arDaniel; # <---
By this assignment, you want change the original array, but with this assignment by value, you in fact create a copy of $arDaniel, and new elements are added only to $arr, not to $arDaniel; to do this, you have to do an assignment by reference through & keyword: replace this (and following similar) line with $arr = &$arDaniel;
}
elseif (j == 1) { # <--- see above
$name = 'Andi';
$arr = $arAndi; # <--- see above
}
elseif (j == 2) { # <--- see above
$name = 'Dave';
$arr = $arDave; # <--- see above
}
elseif (j == 3) { # <--- see above
$name = 'Simon';
$arr = $arSimon; # <--- see above
}
$query = "SELECT Datum, ID, RR, RL, KB, BD, SD, KH, Reihenfolge FROM $name ORDER BY date(Datum)";
$i = 1; # <---
The query is formally correct, but I don't know your table structure. $i = 1; is unnecessary (see below);
foreach($res = $db->query($query) as $value) {
$curr = array();
array_push($curr["Datum"] = $value[0]); # <---
array_push($curr["ID"] = $value[1]); # <---
array_push($curr["RR"] = $value[2]); # <---
array_push($curr["RL"] = $value[3]); # <---
array_push($curr["KB"] = $value[4]); # <---
array_push($curr["BD"] = $value[5]); # <---
array_push($curr["SD"] = $value[6]); # <---
array_push($curr["KH"] = $value[7]); # <---
array_push($curr["Reihenfolge"] = $value[8]); # <---
array_push($arr[$i] = $curr); # <---
$i++; # <---
}
}
The array_push syntax is not correct (see manual page): the correct syntax is array_push( $existentArray, $newElement ). In addition, you can't use array_push to add an associative value, you can use it only for numeric key. Change $curr assignments simply in $curr['Datum'] = $value[0]; etc...
To append $curr to $arr, you have to change the line in array_push( $arr, $curr ) or (better, as php recommends if only one element is appended) $arr[] = $curr;. After these changes, the $i++; line can be deleted.
$json = array(
"Daniel" => $arDaniel,
"Andi" => $arAndi,
"Dave" => $arDave,
"Simon" => $arSimon
);
echo json_encode($json);
$db = NULL;
Now your script is clean (I hope).
Your script remain a bit redundant. You can simplify it in this way:
$array = array( 'Daniel'=>array(), 'Andi'=>array(), 'Dave'=>array(), 'Simon'=>array() );
foreach( $array as $key => &$val )
{
$query = "SELECT Datum, ID, RR, RL, KB, BD, SD, KH, Reihenfolge FROM $key ORDER BY date(Datum)";
$result = $db->query( $query );
$val = $result->fetchAll( PDO::FETCH_ASSOC );
}
$json = json_encode( $array );
echo $json;
By this way, you init an array with names as key, then, in a foreach loop by reference (&$val) you perform a sql query searching in table $key and you fetch all results directly in array (in this example the values are stored as associative arrays, like in your example, but you can use PDO::FETCH_OBJ to store data as object). At the end, you encode the array end echo it.
Edit:
I see a previous answer nearly identical to mine...
BTW, I leave mine because I have spent a lot of time to explain various errors...

Insert to array new key/value php

How
$arr = array ();
while ($obj = mysql_fetch_object($result))
$arr[] = $obj;
// add new key/value in same index
$arr['key'] = 'value';
echo json_encode ($arr);
In this construction not be result like I need
{
0 = {
author = 3;
id = 3;
reader = 3;
review = 4;
};
key = "value";
}
I need:
{
author = 3;
id = 3;
reader = 3;
review = 4;
key = "value";
}
It looks like your query is only returning 1 row, so you don't need the while loop.
First things first though, please don't use mysql_*. Look into MySQLi or PDO
This is what you want instead:
$db = new mysqli(/* host, user, pass, db */);
$result = $db->query("SELECT * FROM aTable LIMIT 1");
$arr = $result->fetch_assoc();
$arr['key'] = 'value';
Edit: Ima go ahead and force you to use mysqli...
Move the value-assigning code into the loop, if you need to add some key-value pair to each and every item of the resulting array:
$arr = array ();
while ($obj = mysql_fetch_object($result))
$obj->key = 'value';
$arr[] = $obj;
}

Dynamic Array with PHP

Post Updated
I would like to create dynamic Array in PHP to provide the same output like static Array below, I have tried to do it with while statement but it doesn't work. Could you please provide me some tips?
I would like to use 2 values from MySQL and save them in to $to variable
so first send_to1 (user account) and then value1 (amount)
<?php
$con=mysqli_connect("localhost","test","test","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM users");
$to=Array(
while($row = mysqli_fetch_array($result))
{
$send_to1 => $value1,
$send_to2=> $value2
}
);
mysqli_close($con);
?>
It's as simple as just adding elements to the array:
//Setup blank array
$example = array();
//Create a loop, for example purposes.
foreach(range(0, 99) as $i){
//Create random variable that we'll add to our array
$randVar = mt_rand(1, 90000);
//$i will be our array key/index
$example[$i] = randVar;
}
//var_dump the array so you can see the structure / end result
var_dump($example);
You could also create it like so:
//Create random array key/index
$myRandKey = mt_rand(1, 90000);
//Create random variable value.
$myRandVar = mt_rand(1, 90000);
//Setup an array
$example = array(
$myRandKey => $myRandVar
);
//Another array key that we'll add to our array
$secondKey = 'test';
//Add it
$example[$secondKey] = 'This is just an example!';
//Dump out the array
var_dump($example);
array_push will also work (using mysql_fetch_assoc, like in your example):
$example = array();
while($row = mysql_fetch_assoc($result)){
array_push($example, $row);
}
var_dump($example);
In your particular example (since you added your code):
print_r($new_array[] = $row[]);
should be changed to:
print_r($new_array[] = $row);
In your code, I'd change it to:
$new_array = array();
while($row = mysqli_fetch_array($result)){
$new_array[] = $row;
}
Or, if you want to key your array by a unique column (Primary key, for example):
$new_array = array();
while($row = mysqli_fetch_array($result)){
$new_array[$row['id']] = $row;
}
Look, this is so easy, you just need to pay more attention to the answers you're getting here.
Here is the simplest way you can do it:
$to = array();
$to[] = array($send_to1 => $value1);
$to[] = array($send_to2 => $value2);
while ( $row = mysqli_fetch_array($result) ) {
$to[] = array($row['send_tox' => $row['valuex']);
}
You need to first understand how Arrays and Loops work in PHP, then try to make a dynamic array in a loop.
Actually you almost got it. It's lower A in 'array'
To initialize an empty array:
$to = array();
In your case (you already have some values), you can do:
$to = array(
$send_to1 => $value1,
$send_to2=> $value2
);
In either case, you can later add more elements doing
$to[$someOtherKey] = $someOtherValue;

MySQLi - search through an array

I have the following code:
function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$query = 'SELECT q17, COUNT(q17) FROM tresults GROUP BY q17';
$result = $mysqli->query($query);
$rows = resultToArray($result);
//print_r($rows); // Array of rows
$result->free();
Brings back the following (only an excerpt):
Array ( [0] => Array ( [q17] => [COUNT(q17)] => 7 ) [1] => Array ( [q17] => Admin & Clerical [COUNT(q17)] => 118 )......etc.
What I am struggling with is how to then return the data, basically, what I need is some code to pull out the data as follows:
WHERE Array = Admin & Clerical BRING BACK THE COUNT(q17) number
How do I search through the array, normally, I'd use something like:
if($rows['q17']==$q[$i]){echo$rows['COUNT(q17)'];}
But this doesn't work - I assume because there are two sets of data within each part of the array? Not sure how to deal with this.
You can achieve this by using MYSQL itself, by using HAVING clause instead of WHERE.
To do this rewrite your query like this.
$query = 'SELECT q17, COUNT(q17) as qcount FROM tresults GROUP BY q17 HAVING q17="Admin & Clerical" ';
echo $row[0]['qcount']; //return 118
if you still want to it with PHP after getting the result from the database, it's how it done:
function get_q17_count($rows, $q17){
foreach ($rows as $onerow) {
if($onerow['q17'] == $q17){
return $onerow['COUNT(q17)'];
}
}
}
function resultToArray($results) {
$rows = array();
while($row = $results->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$querys = 'SELECT q17, COUNT(q17) FROM tresults GROUP BY q17';
$results = $mysqli->query($querys);
$rows = resultToArray($results);
//print_r($rows); // Array of rows
$results->free();
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['q17'] === $id) {
return $val['COUNT(q17)'];
}
}
return null;
}
Called the function using:
$id = searchForId($q[$i], $rows);echo " (".$id.")";

php string name as variable in array

how take string from array define as new array,
how to code in php
$column = array("id","name","value");
let say found 3 row from mysql
want result to be like this
$id[0] = "1";
$id[1] = "6";
$id[2] = "10";
$name[0] = "a";
$name[1] = "b";
$name[2] = "c";
$value[0] = "bat";
$value[1] = "rat";
$value[2] = "cat";
I want to take string from $column array define as new array.
how to code it?
or if my question is stupid , my please to have suggestion.
thank you.
Answer I made on your previous question:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
$i = 0;
if ($num > 0) {
while ($row = mysql_fetch_assoc($result)) {
foreach($row as $column_name => $column_value) {
$temp_array[$column_name][$i] = $column_value;
}
$i++;
}
foreach ($temp_array as $name => $answer) {
$$name = $answer;
}
}
I can't see why you'd want to model your data like this, you're asking for a world of hurt in terms of debugging. There are "variable variables" you could use to define this, or build global variables dynamically using $GLOBALS:
$somevar = "hello"
$$somevar[0] = "first index"; // creates $hello[0]
$GLOBALS[$somevar][0] = "first index"; // creates $hello[0] in global scope
try
$array = array();
foreach ($results as $r){
foreach ($column as $col ){
$array[$col][] = $r[$col];
}
}
extract ($array);
or you can simply do this
$id = array();
$name = array();
$value = array();
foreach ( $results as $r ){
$id[] = $r['id']; // or $r[0];
$name[] = $r['name'];
$value[] = $r['value'];
}
Hope this is what you asked
This is pretty dangerous, as it may overwrite variables you consider safe in your code. What you're looking for is extract:
$result = array();
while ($row = mysql_fetch_array($result))
foreach ($column as $i => $c)
$result[$c][] = $row[$i];
extract($result);
So, if $result was array( 'a' => array(1,2), 'b' => array(3,4)), the last line defines variables $a = array(1,2) and $b = array(3,4).
You cannot use variable variables right on for this, and you shouldn't anyway. But this is how you could do it:
foreach (mysql_fetch_something() as $row) {
foreach ($row as $key=>$value) {
$results[$key][] = $value;
}
}
extract($results);
Ideally you would skip the extract, and use $results['id'][1] etc. But if you only extract() the nested array in subfunctions, then the local variable scope pollution is acceptable.
There is no need for arrays or using $_GLOBALS, i believe the best way to create variables named based on another variable value is using curly brackets:
$variable_name="value";
${$variable_name}="3";
echo $value;
//Outputs 3
If you are more specific on what is the array you receive i can give a more complete solution, although i must warn you that i have never had to use such method and it's probably a sign of a bad idea.
If you want to learn more about this, here is a useful link:
http://www.reddit.com/r/programming/comments/dst56/today_i_learned_about_php_variable_variables/

Categories