Value not saving in array - php

I have an array which have this structure:
$queues[n] Array (
[id] => integer
[idClient] => integer
[name] => string
[people] => integer )
Which is populated with:
$query = "SELECT clients.idClient AS 'idClient', queues.idQueue AS 'idQueue', queues.name AS 'name' FROM clients, queues WHERE clients.idClient = queues.client";
$queues = null;
$result = mysql_query($query);
if ($result){
while ($queue = mysql_fetch_assoc($result)){
$queues[] = array ("idClient" => $queue['idClient'], "id" => $queue['idQueue'], "name" => $queue['name'], "people" => 0);
}
}
Each 'n' value match a queue from Database and people, by default is set to 0.
After populating the array I query the database again with each queue to other table to obtain the number of people in queue with a query like this:
SELECT COUNT(*) FROM peoplequeued WHERE queue ='".$queue['name']."'
And then:
$result = mysql_query($query);
if ($result){
$num_people = mysql_fetch_row($result);
$queue['people'] = $num_people[0];
}
And something strange happens here. If I echo the $queue['people'] in the foreach, it shows fine the value it got but if I preview the full array before returning it, it's back to 0.
What could be happening?

My guess is that you're looping through $queues with foreach loop like this:
foreach ( $queues as $queue ) {
$result = mysql_query($query);
if ($result){
$num_people = mysql_fetch_row($result);
$queue['people'] = $num_people[0];
}
}
If so, there's no "link" between $queue and $queues[$n], i.e., by modifying $queue, you do NOT modify $queues.
If this is the case, you should either use $queue as reference variable, or modify $queues[$n] with $n being an index.
foreach ( $queues as &$queue ) { // add & so $queue is a reference to an element in $queues
$result = mysql_query($query);
if ($result){
$num_people = mysql_fetch_row($result);
$queue['people'] = $num_people[0];
}
}
unset($queue); // drop the reference, otherwise you might have unexpected results after modifying $queue outside the loop
... or ...
foreach ( $queues as $n => $queue ) { // store index of "current" element in $n
$result = mysql_query($query);
if ($result){
$num_people = mysql_fetch_row($result);
$queues[$n]['people'] = $num_people[0]; // change $queue to $queues[$n]
}
}
Alternatively, I would advise you to think about getting all data in a single statement. It looks like something like this might work for you:
select
baseTable.id,
baseTable.idClient,
baseTable.name,
peopleCount.count as people
from
baseTable
left join (
select
count(*) as count,
queue
from
peoplequeued
group by
queue
) as peopleCount on peopleCount.queue = baseTable.name

It sounds like you're probably using a foreach loop to cycle through your $queues array, like this:
foreach($queues as $queue) {
}
Each $queue variable generated is a copy, and changes to it aren't saved to the $queues variable. To save changes as you're intending, you need to do something like:
foreach($queues as $k => $queue) {
$queue['people'] = 10;
$queues[$k] = $queue;
// or, more efficiently...
$queues[$k]['people'] = 10;
}
In PHP5 you can also reference. See http://uk.php.net/manual/en/control-structures.foreach.php

Related

How to extract value from foreach loop by json_encode

I have php result set, and from these result i am extracting value using php foreach loop. I put the foreach loop value in array $summery[]. but when i try to print value its print value at once. but i need separate value/result set for each foreach loop as json code so that i can print each result separately. My foreach loop following :
foreach($result_UserWrSet as $UserWrInfo) {
$summery[]=$UserWrInfo['wr_id'];
$summery[]=$UserWrInfo['wr_number'];
$summery[]=$UserWrInfo['wr_title'];
$dateFlag=1;
$result_StartDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$result_EndDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$summery[]=$result_StartDate;
$sql_GetUserName = "SELECT user_name FROM user_information where user_id='$UserWrInfo[user_id]'";
$result_GetUserName = mysqli_query($conn, $sql_GetUserName);
$num_GetUserName = mysqli_num_rows($result_GetUserName);
if ($num_GetUserName > 0){
$UserNameByIdRos = $result_GetUserName->fetch_assoc();
$UserNameById=$UserNameByIdRos['user_name'];
}
else {$UserNameById=NULL;}
$summery[]=$UserNameById;
$result_CurrentHop = $WrDates ->getCurrentHopByWrId($UserWrInfo['wr_id']);
$result_CurrentHopName = $WrDates ->GetHopsNameById($result_CurrentHop);
$summery[]=$result_CurrentHopName;
$result_EndDate = $WrDates ->completedDate($UserWrInfo['wr_id']);
$summery[]=$result_EndDate;
}
print json_encode($summery);
My result become
["69","010116-69","Wr test","01\/01\/16 18:45 PM","planner","Done","01\/01\/16 19:16 PM","68","010116-","This is title","01\/01\/16 18:44 PM","planner","Done"]
but i need :
[["69","010116-69","Wr test","01\/01\/16 18:45 PM","planner","Done"],["01\/01\/16 19:16 PM","68","010116-","This is title","01\/01\/16 18:44 PM","planner","Done"]]
Use this code, you need to use another array in which all the sub array's to be pushed and encode that array after pushing all the items into it
<?php
$dataArray = array(); /// empty array in which sub array's to be pushed..
foreach($result_UserWrSet as $UserWrInfo) {
$summery= array();
$summery[]=$UserWrInfo['wr_id'];
$summery[]=$UserWrInfo['wr_number'];
$summery[]=$UserWrInfo['wr_title'];
$dateFlag=1;
$result_StartDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$result_EndDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$summery[]=$result_StartDate;
$sql_GetUserName = "SELECT user_name FROM user_information where user_id='$UserWrInfo[user_id]'";
$result_GetUserName = mysqli_query($conn, $sql_GetUserName);
$num_GetUserName = mysqli_num_rows($result_GetUserName);
if ($num_GetUserName > 0){
$UserNameByIdRos = $result_GetUserName->fetch_assoc();
$UserNameById=$UserNameByIdRos['user_name'];
}
else {$UserNameById=NULL;}
$summery[]=$UserNameById;
$result_CurrentHop = $WrDates ->getCurrentHopByWrId($UserWrInfo['wr_id']);
$result_CurrentHopName = $WrDates ->GetHopsNameById($result_CurrentHop);
$summery[]=$result_CurrentHopName;
$result_EndDate = $WrDates ->completedDate($UserWrInfo['wr_id']);
$summery[]=$result_EndDate;
////Push sub array i.e summary into the main array...
$dataArray[] = $summery;
}
print json_encode($dataArray);
?>
You need a multidimensional array, you can follow below code:
$result_UserWrSet = array(
'0' => array('wr_id'=>'12','wr_number' =>'785', 'wr_title' => 'title1'),
'1' => array('wr_id'=>'12','wr_number' =>'785', 'wr_title' => 'title1'));
foreach($result_UserWrSet as $key => $UserWrInfo) {
$summery[$key][]=$UserWrInfo['wr_id'];
$summery[$key][]=$UserWrInfo['wr_number'];
$summery[$key][]=$UserWrInfo['wr_title'];
}
print json_encode($summery);
output: [["12","785","title1"],["12","785","title1"]]
Good Luck :)
Currently, you are just adding new items to a one dimensional array. You need to create a separate array per result, like this:
foreach($result_UserWrSet as $UserWrInfo) {
$item = array();
// Change all $summary in the loop to: $item, like this:
$item[]=$UserWrInfo['wr_id'];
$item[]=$UserWrInfo['wr_number'];
$item[]=$UserWrInfo['wr_title'];
//...and so on
// Then add this last in your loop:
$summary[] = $item;
}
This will create one array per iteration that is put in the main array, which then becomes a multi dimensional array.

PDO: PHP foreach array returning null

I did a very short and simple PHP .
The output is an array in json. However it doesn't work .
The array-items are always null.
I guess it must have something to do with mistakenly calling the db table columns
('id' => $row->MASTER_ID).
Whereas 'MASTER_ID' is the name of the column in my db.
I'd be very glad if someone could point me in the right direction.
My script looks as follows:
<?php
$db = new PDO('mysql:host=xxx;dbname=xx;charset=utf8mb4', 'xx', 'xxx');
$month = date('Y-m');
$monthwild = "$month%";
$sql = ("SELECT * FROM MASTER WHERE START_DATE LIKE '". $monthwild ."'");
$out = array();
foreach($db->query($sql) as $row) {
$out[] = array(
'id' => $row->MASTER_ID,
'title' => $row->MASTER_TITLE,
'start' => strtotime($row->MASTER_START),
'end' => strtotime($row->MASTER_END)
);
}
echo json_encode(array('success' => 1, 'result' => $out));
exit;
?>
I'm new to PDO (used to do things like this with mysql) and
I didn't get it yet and didn't find the right resources
PDO::query “executes an SQL statement, returning a result set as a PDOStatement object,” not a row.
You have to put the result in a variable and then retrieve rows from this variable:
$result = $db->query( $sql );
while( $row = $result->fetchObject() )
{
(...)
}
As alternative, you can set a default fetch mode and then retrieve single rows with:
$result = $db->query( $sql );
$result->setFetchMode( PDO::FETCH_OBJ );
while( $row = $result->fetch() )
{
(...)
}
Edit:
Actually, also direct foreach works, but without a specific fetch mode it returns enumerated and associative result:
foreach( $db->query( $sql ) as $row )
{
$id = $row['MASTER_ID'];
// $id = $row[0]; // ← Alternative
}
To use objects with direct foreach you have to use this syntax:
foreach( $db->query( $sql, PDO::FETCH_OBJ ) as $row )
{
$id = $row->MASTER_ID;
}
Read more about PDO::query
Read more about PDOStatement
I'd say that your definition of $monthwild is wrong.
The right notation for that what you want to write is:
$monthwild = $month."%";
In your script is the content of $monthwild the string "$month%"
Now is the content of $monthwild the string %
I hope you can understand that.
It is not easily described.

Add data in a multidimensional array dynamically

I am needing to add data dynamically into a multidimensional array. The data comes from a query in the database. I can see through the "echo" all elements, but in time to add to the multidimensional vector data and overwrite only the last record is added.
My example below:
$queryu = "SELECT * FROM usuario ORDER BY id";
$stmtu = $con->prepare($queryu);
$stmtu->execute();
$numu = $stmtu->rowCount();
$j = 0;
$lista;
if ($numu > 0) {
$colunas = 3;
while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
extract($rowu);
$lista['id'] = $id;
$lista['nome'] = $nome;
$j++;
}
}
The result:
id - 6
nome - teste
This is the last record added.
Thanks!!!
You don't create a multi dimensional array by now. You just update create two key => value pairs id and nome. If you want to store multiple of them you have to create a multidimensional array which means an array inside another array:
$lista = array(); // init your array!
while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
extract($rowu);
$lista[] = array(
'id' => $id,
'nome' => $nome
);
$j++;
}
Or do it even smarter (if the keys in the final array are the same as the column names):
$lista = array(); // init your array!
while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
$lista[] = $rowu;
$j++;
}
Modify your code as follows
$queryu = "SELECT * FROM usuario ORDER BY id";
$stmtu = $con->prepare($queryu);
$stmtu->execute();
$numu = $stmtu->rowCount();
$lista = array();
if ($numu > 0) {
$colunas = 3;
while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
extract($rowu);
$lista[] = array('id' => $id, 'nome' => $nome);
}
}
As you probably noticed here, I've removed j index (you don't need it; I suppose that you would use it as "first-level-index" of your multidimensional array) and added that statement: $lista[] =. "Magic" happens just there: with this command ($arrayname[] =) you can append to existent array a new element.
However I don't know from where you're obtaining $id and $nome so this snippet could fail due to undefined variables and similar

Return MySQL rows in array

I've been working on a OOP method that is supposed to return the rows of a MySQL query. I have to have the data array in the format:
$rows = array('row'=> rownum, 'fld1'=> fldval .... 'fldn' => fldval);
What I have encountered are the two problems of either:
returns
$rows = array('0'=>fldval, 'fld1'=> fldval .... 'n'=> fldval, 'fldn' => fldval);
or single row of
$rows = array('fld1'=> fldval .... 'fldn' => fldval);
Little frustrated as every PHP mysql function I have tried has some sort to goofy crap flaw and will not do a straight out process.
I assume there is a good example somewhere, that can get me past the crap limitations, but haven't found anything useful yet!
I've tried all of the following:
$row = mysql_result($db_res,$n);
$row = mysql_fetch_array($db_res);
$row = mysql_fetch_assoc($db_res);
$row = mysql_fetch_object($db_res);
$row = mysql_fetch_row($db_res);
None have worked successfully! For getting out the bogus "numeric" array entries. I wrote:
foreach ($row as $k => $v)
if (is_numeric($k)) { continue; }
$result[$k] = $v;
} // end foreach $row
$row = array_push($row, 'row'=>$rownum, $result);
Hoping someone has a link.
$list = array();
$query = "SELECT value FROM table";
$resource = mysql_query($query);
while($row = mysql_fetch_assoc($resource))
{
$list['fld' . (1 + count($list))] = $row['value'];
}
$list = array('row' => count($list)) + $list;
if table have 3 row, the code above is going to give you a array like:
array(
'row' => 3,
'fld1' => 12,
'fld2' => 34,
'fld3' => 56
);

Why my php array is over written when they have same Keys

I have a custom PHP function which executes a stored procedure and returns an array:
function test(){
$in = array("abc","bcd","efg");
$result = mydba->executestoredprocedure('proc1',$in);
$arr_sim = array();
foreach ($result['recordset'] as $rows) {
if (!empty($rows)) {
echo $arr_sim[$rows['field1']] = $rows['field2'];
}
}
return $arr_sim;
}
In the above function $arr_sim is returning the number of items correctly when the rows["field1"] values are different. If the rows["field1"] values are the same then it is overwriting the first value and returning only the last one. How can I overcome this?
array ( [chicago] => 'sears', [rochester] => 'liberty' )
If the $arr_sim contains these items then it is returned correctly. Because the keys are different.
array ( [chicago] => 'MCD', [chicago] => 'TACOBELL' )
If the $arr_sim contains these items then it is not returned correctly. Because the keys are the same, "chicago".
Array keys must be unique. Instead, do something like this:
// You want the array to look like this
// array('chicago' => array('MCD', 'TACOBELL'));
function test(){
$in = array("abc","bcd","efg");
$result = mydba->executestoredprocedure('proc1',$in);
$arr_sim=array();
foreach ($result['recordset'] as $rows) {
if(!empty($rows)){
if(array_key_exists($rows['field1'], $arr_sim) {
$arr_sim[$rows['field1']][] = $rows['field2'];
} else {
$arr_sim[$rows['field1']] = array($rows['field2']);
}
}
}
return $arr_sim;
}
Replace $arr_sim[$rows['field1']] = $rows['field2'] with $arr_sim[$rows['field1']][] = $rows['field2']. This will create an array of arrays.
echo $arr_sim['chicago'][0]; // MCD
echo $arr_sim['chicago'][1]; // TACOBELL
Technically, you should write something like this to avoid notices:
if (!isset($arr_sim[$rows['field1']])) $arr_sim[$rows['field1']] = array();
$arr_sim[$rows['field1']][] = $rows['field2'];
But you must really ask yourself, is the field1 (city names) worthy of being the primary key for the array? If not, you should choose some other identifier.

Categories