I am working on a web app using php. I am trying to pull from a database and fill an array with the information then encode it to json.
Here is what I have so far:
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
$frats = array();
while ($row = mysqli_fetch_array($result)) {
$frat->name = $row['name'];
$frat->description = $row['description'];
$frat->chapter = $row['chapter'];
$frat->members = $row['members'];
$frat->cover_image = $row['cover_image'];
$frat->profile_image = $row['profile_image'];
$frat->calendar_image = $row['calendar_image'];
$frat->preview_image = $row['preview_image'];
$frat->address = $row['address'];
$frats[] = $frat;
}
echo json_encode($frats);
What I get in return is in the correct json format I want with the correct keys and everything, but every item in the json is the same. All of them are the last one. I believe this is because I might just be referencing the values, but I am not sure how to actually copy them in php.
Any suggestions?
you need to create a new instance of $frat inside the loop. Otherwise you are just updating the original $frat each time the loop runs and adding a reference to it in the array.
Assuming its not a static class you could use:
$frats = array();
while ($row = mysqli_fetch_array($result)) {
$frat = new frat();
$frat->name = $row['name'];
$frat->description = $row['description'];
$frat->chapter = $row['chapter'];
$frat->members = $row['members'];
$frat->cover_image = $row['cover_image'];
$frat->profile_image = $row['profile_image'];
$frat->calendar_image = $row['calendar_image'];
$frat->preview_image = $row['preview_image'];
$frat->address = $row['address'];
$frats[] = $frat;
}
echo json_encode($frats);
Even better would be to modify the constructor or create a method to consume the data. If you used the class's constructor then you could do something like this:
$frats = array();
while ($row = mysqli_fetch_array($result)) {
$frats[] &= new frat($row['name'], $row['description'], $row['chapter']);
}
echo json_encode($frats);
In the first line inside your while loop, you simply need the following line:
$frat = new \stdClass();
You need to properly declare your variables $frats (array) and $frat (object):
$frats = array();
while ($row = mysqli_fetch_array($result)) {
$frat = (object) array();
$frat->name = $row['name'];
$frat->description = $row['description'];
$frat->chapter = $row['chapter'];
$frat->members = $row['members'];
$frat->cover_image = $row['cover_image'];
$frat->profile_image = $row['profile_image'];
$frat->calendar_image = $row['calendar_image'];
$frat->preview_image = $row['preview_image'];
$frat->address = $row['address'];
array_push($frats, $frat); // For backward compatiblity
}
echo json_encode($frats);
Related
I have my response where I want to fill below.
$response = array(
"year" => array(),
"playerName" => array(),
"cardVariation" => array()
);
I have a simple query to my table.
$sql = "SELECT * from $TBL";
$result = $conn->query($sql);
I will then lop through my results.
while($row = $result->fetch_assoc()) {
$year = $row['year'];
$playerName = $row['name'];
$cardVariation = $row['cardV'];
// add to response
$response['year'] = $year;
$response['name'] = $playerName;
$response['cardV'] = $cardVariation;
}
echo json_encode($response);
Expected response:
{"year": ["1999", "2000"], "name": ["bill", "jess"], "cardV": ["base","silver"]}
Only the last one gets added. I couldn't find an "append" method for PHP, unless i looked over it.
You are over writing the values each time round the loop so place the values into a new occurance each time by using $response['year'][] = . Also you are wasting time moving values into scalar variables.
while($row = $result->fetch_assoc()) {
// add to response
$response['year'][] = $row['year'];
$response['name'][] = $row['name'];
$response['cardV'][] = $row['cardV'];
}
You can use array_push() or just
$response['year'][] = $year;
$response['name'][] = $playerName;
$response['cardV'][] = $cardVariation;
https://www.php.net/manual/de/function.array-push.php
I have a query that I execute, then I use
while($row = $result->fetch_assoc()){
$data[] = $row;
I know this is grotesque, but I'm unsure how to make this an object or a multidimensional array so I just made something like this..
$NUH2016 = array();
$NUH2017 = array();
$NUH2018 = array();
$NUH2019 = array();
$NUH2020 = array();
$NUH2021 = array();
$RBN2016 = array();
$RBN2017 = array(); ...
...$GDT2019 = array();
$GDT2020 = array();
$GDT2021 = array();
while($row = $result->fetch_assoc()){
$data[] = $row;
if($row['Location'] == 'NUH' && $row['Year'] == '2016'){
$NUH2016[] = $row['P_1'];
$NUH2016[] = $row['P_2'];
$NUH2016[] = $row['P_3'];
$NUH2016[] = $row['P_4'];
}
if($row['Location'] == 'NUH' && $row['Year'] == '2017'){
$NUH2017[] = $row['P_1'];
$NUH2017[] = $row['P_2'];
$NUH2017[] = $row['P_3'];
$NUH2017[] = $row['P_4'];
}
//...for all locations and years
...then
$content = array();
$results = array();
$NUH2016_total = array_sum($NUH2016);
$NUH2017_total = array_sum($NUH2017);
$NUH2018_total = array_sum($NUH2018);
$NUH2019_total = array_sum($NUH2019);
$NUH2020_total = array_sum($NUH2020);
$NUH2021_total = array_sum($NUH2021);
$results['NUH~2016'] = $NUH2016_total;
$results['NUH~2017'] = $NUH2017_total;
$results['NUH~2018'] = $NUH2018_total;
$results['NUH~2019'] = $NUH2019_total;
$results['NUH~2020'] = $NUH2020_total;
$results['NUH~2021'] = $NUH2021_total;
$RBN2016_total = array_sum($RBN2016);
$RBN2017_total = array_sum($RBN2017);
$RBN2018_total = array_sum($RBN2018);
$RBN2019_total = array_sum($RBN2019);
$RBN2020_total = array_sum($RBN2020);
$RBN2021_total = array_sum($RBN2021);
$results['RBN~2016'] = $RBN2016_total;
$results['RBN~2017'] = $RBN2017_total;
$results['RBN~2018'] = $RBN2018_total;
$results['RBN~2019'] = $RBN2019_total;
$results['RBN~2020'] = $RBN2020_total;
$results['RBN~2021'] = $RBN2021_total;
...etc
$content['Results'] = $results;
$response = json_encode($content);
echo $response;
So what I want to do is make an object or associative array that looks like this.
content {
produced hours{
nuh{ 2016:16,000
2017:8,000
...
}
rbn{ 2016:9,000
2017:whatever
....
}
man hours{
nuh{ 2016:4,000
2017:2,000
...
}
rbn{ 2016:1,000
2017:more stuff
....
}
but I'm pretty new to php objects. How can I refactor it so that I don't have to initialize every single empty array, have a bunch of if statements to make each entry from the query fit into an array to be summed, and then put it all into an object at the end to get back from an ajax success function?
There's no need to declare so many arrays. Simply change your while() loop in the following way,
$resultArr = array();
while($row = $result->fetch_assoc()){
$tmpArr = array($row['P_1'], $row['P_2'], $row['P_3'], $row['P_4']);
$sumTotal = array_sum($tmpArr);
$tmpArr['sumTotal'] = $sumTotal;
$resultArr[$row['Location']][$row['Year']][] = $tmpArr;
}
Later, apply json_encode() on the result array like this,
$json = json_encode($resultArr);
Sidenote: If you want to see the complete array structure, do var_dump($resultArr);
You can have an array of arrays, so you don't need to manually assign them all.
$LocationAndYears;
while($row = $result->fetch_assoc())
{
$LocationAndYears[$row['Location']] [$row['Year']] [0] = $row['P_1'];
$LocationAndYears[$row['Location']] [$row['Year']] [1] = $row['P_2'];
$LocationAndYears[$row['Location']] [$row['Year']] [2] = $row['P_3'];
$LocationAndYears[$row['Location']] [$row['Year']] [3] = $row['P_4'];
$LocationAndYears[$row['Location']] [$row['Year']] ['sum'] = array_sum($LocationAndYears[$row['Location']] [$row['Year']]);
}
echo $LocationAndYears['NUH']['2012'][0];
echo "Sum for 2012 at NUH:" . $LocationAndYears['NUH']['2012']['sum'];
print_r($LocationAndYears);
Without writing the whole thing, look into multi-dimensional arrays.
Something like this maybe...
But really I think the answer to this is to point you at multi-dimensional arrays as it's very vague
$data = array();
while($row = $result->fetch_assoc()){
$location = $row['Location'];
$year = $row['Year'];
$data[$location] = $data[$location] ? $data[$location] : array();
$data[$location][$year] = $data[$location][$year] ? $data[$location][$year] : array();
$data[$location][$year][] = $row['P_1'];
$data[$location][$year][] = $row['P_2'];
$data[$location][$year][] = $row['P_3'];
$data[$location][$year][] = $row['P_4'];
}
I am attempting to use a Manager Class to take the results of a query and do formatting on pieces of information so I don't have to have logic on my view. I googled a number of solution and thought this would work, but my Array of Key=>values is coming back blank. Can someone take a look at it and see what i am doing wrong? Thanks!
I have verified that $results contains the values I am attempting to format and place back into an Array.
while($row = mysqli_fetch_array($results)){
$pets[$row['petID']] = $row['petID'];
$pets[$row['chipID']]=$row['chipID'];
$pets[$row['adoptionDate']]=Date($row['adoptionDate'],'m-d-Y');
$pets[$row['pType']]=$row['pType'];
$pets[$row['breedName2']]=$row['breedName2'];
$pets[$row['breedName1']]=$row['breedName1'];
$pets[$row['imageName']]=$row['imageName'];
$pets[$row['intakeDate']]= Date($row['intakeDate'],'m-d-Y');
$pets[$row['status']]=$row['status'];
$pets[$row['age']]=$row['age'];
$pets[$row['ageText']]= $this->getAge($row['age']);
$pets[$row['gender']]=$row['gender'];
$pets[$row['genderText']] = $this->getGender($row['gender']);
$pets[$row['breed2']]=$row['breed2'];
$pets[$row['breed']]=$row['breed'];
$pets[$row['petType']]=$row['petType'];
$pets[$row['petName']]=$row['petName'];
$pets[$row['customID']]=$row['customID'];
}
Here is the complete function that does not return anything:
public function getPets($cond,$orgID){
$pets = array();
$pg = new petsGateway();
$results = $pg->listByQuery($cond, $orgID);
while($row = mysqli_fetch_array($results)){
$pets[$row['petID']] = $row['petID'];
$pets[$row['chipID']]=$row['chipID'];
$pets[$row['adoptionDate']]=Date($row['adoptionDate'],'m-d-Y');
$pets[$row['pType']]=$row['pType'];
$pets[$row['breedName2']]=$row['breedName2'];
$pets[$row['breedName1']]=$row['breedName1'];
$pets[$row['imageName']]= $this->getImageURL($row['imageName']);
$pets[$row['intakeDate']]= Date($row['intakeDate'],'m-d-Y');
$pets[$row['status']]=$row['status'];
$pets[$row['age']]=$row['age'];
$pets[$row['ageText']]= $this->getAge($row['age']);
$pets[$row['gender']]=$row['gender'];
$pets[$row['genderText']] = $this->getGender($row['gender']);
$pets[$row['breed2']]=$row['breed2'];
$pets[$row['breed']]=$row['breed'];
$pets[$row['petType']]=$row['petType'];
$pets[$row['petName']]=$row['petName'];
$pets[$row['customID']]=$row['customID'];
}
return $pets;
}
That's rather... repetitive code... wouldn't it be easier to modify your query to fetch the rows you want AND do the date formatting directly in the DB?
e.g.
SELECT rowID, ... DATE_FORMAT(adoptionDate, '%m-%d-%Y'), ...
FROM ...
and then
while($row = mysql_fetch_assoc($result)) {
$pets[] = $row;
}
hm.... well im not sure what you want, but as you have it now, the key and the value of your array will be the same, which makes it useless.
i.e. for petName
$pets['Fido'] = 'Fido'
probably you want to get rid of the $row portion of the left side of your assignment, so that you end up with this
while($row = mysqli_fetch_array($results))
{
$pet = Array();
$pet['petID'] = $row['petID'];
$pet['chipID'] = $row['chipID'];
$pet['adoptionDate'] = Date($row['adoptionDate'],'m-d-Y');
$pet['pType'] = $row['pType'];
$pet['breedName2'] = $row['breedName2'];
$pet['breedName1'] = $row['breedName1'];
$pet['imageName'] = $row['imageName'];
$pet['intakeDate'] = Date($row['intakeDate'],'m-d-Y');
$pet['status'] = $row['status'];
$pet['age'] = $row['age'];
$pet['ageText'] = $this->getAge($row['age']);
$pet['gender'] = $row['gender'];
$pet['genderText'] = $this->getGender($row['gender']);
$pet['breed2'] = $row['breed2'];
$pet['breed'] = $row['breed'];
$pet['petType'] = $row['petType'];
$pet['petName'] = $row['petName'];
$pet['customID'] = $row['customID'];
$pets.push($pet);
}
I am guessing but I understood that you want some thing like:
while($row = mysqli_fetch_array($results)){
$pets[$row['petID']]['petID'] = $row['petID'];
$pets[$row['petID']]['chipID'] = $row['chipID'];
$pets[$row['petID']]['adoptionDate'] = Date($row['adoptionDate'],'m-d-Y');
$pets[$row['petID']]['pType'] = $row['pType'];
$pets[$row['petID']]['breedName2'] = $row['breedName2'];
$pets[$row['petID']]['breedName1'] = $row['breedName1'];
$pets[$row['petID']]['imageName'] = $row['imageName'];
$pets[$row['petID']]['intakeDate'] = Date($row['intakeDate'],'m-d-Y');
$pets[$row['petID']]['status'] = $row['status'];
$pets[$row['petID']]['age'] = $row['age'];
$pets[$row['petID']]['ageText'] = $this->getAge($row['age']);
$pets[$row['petID']]['gender'] = $row['gender'];
$pets[$row['petID']]['genderText'] = $this->getGender($row['gender']);
$pets[$row['petID']]['breed2'] = $row['breed2'];
$pets[$row['petID']]['breed'] = $row['breed'];
$pets[$row['petID']]['petType'] = $row['petType'];
$pets[$row['petID']]['petName'] = $row['petName'];
$pets[$row['petID']]['customID'] = $row['customID'];
}
This way you have an array with all the pets ID as first key and its details in the second key. You can use the array push as well.
That will rewrite $pets[KEY] each time it loops through record. You want..
$pets[]['petID'] = $row['petID'];
$pets[]['chipID'] = $row['chipID'];
and so on
I have not worked with arrays much in PHP. I have a table of colors. I want to load it into a multidimensional associative array because I am going to be using that table a lot and don't want to do selects over and over again.
I did:
$result = mysql_query("select * FROM color") or die(mysql_error());
$colors = "";
while($colorrec = mysql_fetch_array($result)){
$colors[$colorrec['ID']][0] = $colorrec['Description'];
$colors[$colorrec['ID']][1] = $colorrec['HexCode'];
}
then when I want to access a colors information, I can just do something like:
echo "color code WHT";
echo "description ".$colors['WHT'][0];
echo "Hex Code ".$colors['WHT'][1];
Is this the correct way/methodology to do this?
$colors = ""; //what?? this should be array()
This should be something like:
$result = mysql_query("select * FROM color") or die(mysql_error());
$colors = array();
while($colorrec = mysql_fetch_array($result)){
$colors[$colorrec['ID']] = array();
$colors[$colorrec['ID']]['Desc'] = $colorrec['Description'];
$colors[$colorrec['ID']]['Hex'] = $colorrec['HexCode'];
}
Then you can do:
echo "color code WHT";
echo "description ".$colors['WHT']['Desc'];
echo "Hex Code ".$colors['WHT']['Hex'];
Sure nothing wrong with going this way. Also if you get lost in your array, just do a quick print_r($array) and it will output the structure for you.
try with:
$result = mysql_query("select * FROM color") or die(mysql_error());
$colors = array();
while($colorrec = mysql_fetch_array($result)){
$colors[$colorrec['ID']] = array(
$colorrec['Description'] ,
$colorrec['HexCode'] );
}
echo "color code WHT";
echo "description ".$colors['WHT'][0];
echo "Hex Code ".$colors['WHT'][1];
Neal you can do as he mentioned, if you want more clean go OOP (PHP5)
class Color
{
$description ="";
$hexcode = "";
$someOther="";
}
$colors = array();
$result = mysql_query("select * FROM color") or die(mysql_error());
while($colorrec = mysql_fetch_array($result))
{
$color = new Color();
$id=$colorrec['HexCode'];
$color->description = $colorrec['Description'];
$color->hexCode = $colorrec['HexCode'];
$colors[$id] = $color;
}
echo $color['ID']->description;
echo $color['ID']->hexCode;
I use it like this:
$numfields = mysql_num_fields($result);
while($red = mysql_fetch_array($result)){
for ($j=0; $j<$numfields; $j++ ) {
$field_name = mysql_field_name($result, $j);
//create Matrix
$datapull[$i][$field_name] = $red[$field_name];
}
$i++;
}
mysql_free_result($result);
var_dump($datapull);
This is more generic and harder to search, it should be used in class method or a function, so you pass the SQL and always expect the same format as a result.
I'd like to think that there's a simple way of doing this. I have over thirty columns in a database that I need to update. All of the columns have the same name as the correlating session variables.
Here's my code to fetch the array and assign variables:
while ($row = mysql_fetch_array($result))
{
$_SESSION['PendingCivil'] = $row['PendingCivil'];
$_SESSION['PendingAsbestos'] = $row['PendingAsbestos'];
$_SESSION['PendingDomestic'] = $row['PendingDomestic'];
$_SESSION['AsgNewCivil'] = $row['AsgNewCivil'];
$_SESSION['AsgNewAsbestos'] = $row['AsgNewAsbestos'];
$_SESSION['AsgNewDomestic'] = $row['AsgNewDomestic'];
$_SESSION['AsgTransferCivil'] = $row['AsgTransferCivil'];
$_SESSION['AsgTransferAsbestos'] = $row['AsgTransferAsbestos'];
$_SESSION['AsgTransferDomestic'] = $row['AsgTransferDomestic'];
$_SESSION['AsgReopenedCivil'] = $row['AsgReopenedCivil'];
$_SESSION['AsgReopenedAsbestos'] = $row['AsgReopenedAsbestos'];
$_SESSION['AsgReopenedDomestic'] = $row['AsgReopenedDomestic'];
$_SESSION['DispWOPCivil'] = $row['DispWOPCivil'];
$_SESSION['DispWOPAsbestos'] = $row['DispWOPAsbestos'];
$_SESSION['DispWOPDomestic'] = $row['DispWOPDomestic'];
$_SESSION['DispFinalCivil'] = $row['DispFinalCivil'];
$_SESSION['DispFinalAsbestos'] = $row['DispFinalAsbestos'];
$_SESSION['DispFinalDomestic'] = $row['DispFinalDomestic'];
$_SESSION['DispBTCivil'] = $row['DispBTCivil'];
$_SESSION['DispBTAsbestos'] = $row['DispBTAsbestos'];
$_SESSION['DispBTDomestic'] = $row['DispBTDomestic'];
$_SESSION['DispJTCivil'] = $row['DispJTCivil'];
$_SESSION['DispJTAsbestos'] = $row['DispJTAsbestos'];
$_SESSION['DispJTDomestic'] = $row['DispJTDomestic'];
$_SESSION['DispTOCivil'] = $row['DispTOCivil'];
$_SESSION['DispTOAsbestos'] = $row['DispTOAsbestos'];
$_SESSION['DispTODomestic'] = $row['DispTODomestic'];
$_SESSION['OldCivil'] = $row['OldCivil'];
$_SESSION['OldAsbestos'] = $row['OldAsbestos'];
$_SESSION['OldDomestic'] = $row['OldDomestic'];
}
Basically I'd like to update each row with a (possibly) changed session variable on an update page. Is there a way to iterate through the session variables and update the corresponding columns? Note: I have other session variables set that are not in the DB.
What about:
while ($row = mysql_fetch_assoc($result))
foreach($row as $k => $v)
$_SESSION[$k] = $v;
fetch them all to associative arrays
while ($row = mysql_fetch_assoc($result)){
foreach($row as $column_name => $data){
$_SESSION[$column_name] = $data;
}
}