Mysql Data Only Pulling Last Result Into Json Array - php

I'm pulling multiple rows from a table and formatting them to this standard: 3 Swords, 5 Daggers, etc.
Well When I try to put that data into a json Array, It's only pulling the last result as this [{"weapons":"You Used: 3 Rusty Dagger's, "}] Which it should say: [{"weapons":"You Used: 3 Rusty Dagger's, 2 Swords"}]
Here's The Query I'm currently using, Which will show perfectly inside of the while loop:
$get_weapons = mysql_query("SELECT
O.player_id,
O.item_id,
O.name,
O.attack,
O.defense,
O.type,
O.owned,
(SELECT
sum(owned) FROM items_owned
WHERE owned <= O.owned AND player_id=$id) 'RunningTotal'
FROM items_owned O
HAVING RunningTotal <= $mob_avail
ORDER BY attack DESC");
// Get Weapon Info
while($weapon = mysql_fetch_array($get_weapons)){
$weapon_id = $weapon['item_id'];
$weapon_name = $weapon['name'];
$weapon_attack = $weapon['attack'];
$weapon_defense = $weapon['defense'];
$weapon_owned = $weapon['owned'];
// Formatting Weapons Message
$weapon_message = 'You Used: '.$weapon_owned.' '.$weapon_name.'\'s, ';
}
$data[] = array('weapons'=>$weapon_message);
echo json_encode($data);
I understand that the $data array is outside of the while loop, But I'm only needing a total of one arrays, so I'm kind of stuck on what to do to fix this issue. Any help would be awesome

You should add one static variable before append the results into the message.
Here is the reference answer:
$get_weapons = mysql_query("SELECT O.player_id, O.item_id, O.name, O.attack, O.defense, O.type, O.owned, (
SELECT sum(owned) FROM items_owned WHERE owned <= O.owned AND player_id=$id) 'RunningTotal' FROM items_owned O HAVING RunningTotal <= $mob_avail ORDER BY attack DESC");
// Initialize the message
$weapon_message = 'You Used: ';
// Get Weapon Info
while($weapon = mysql_fetch_array($get_weapons)){
$weapon_id = $weapon['item_id'];
$weapon_name = $weapon['name'];
$weapon_attack = $weapon['attack'];
$weapon_defense = $weapon['defense'];
$weapon_owned = $weapon['owned'];
// Formatting Weapons Message
$weapon_message = $weapon_message.$weapon_owned.' '.$weapon_name.'\'s, ';
}
$data[] = array('weapons'=>$weapon_message);
echo json_encode($data);

Related

Remove Array From Json in PHP

hi i have a backend with php in cpanel and i have a problem with one of jsons . this is part of my php code :
...
}elseif ($work == "dollardate") {
$query3 = "SELECT * FROM tabl_dollar_date";
$result3 = $connect->prepare($query3);
$result3->execute();
$out3 = array();
while ($row3 = $result3->fetch(PDO::FETCH_ASSOC)) {
$record3 = array();
$record3["dollar"] = $row3["dollar"];
$record3["date"] = $row3["date"];
array_push($out3, $record3);
}
echo json_encode($out3);
}
?>
this code show this in json :
[
{
"dollar":"15000",
"date":"1397-12-12"
}
]
how can remove array from json and show the json like this :
{
"dollar":"15000",
"date":"1397-12-12"
}
Easiest way (according his code):
change line
echo json_encode($out3);
to
echo json_encode($out3[0]);
One solution is that if you just want the latest value (in case there are multiple records in the table), then change the SELECT to order by date descending also set LIMIT to 1 to only get the 1 record anyway, and remove the loop to fetch the data and just fetch the 1 record...
$query3 = "SELECT `date`, `dollar`
FROM `tabl_dollar_date`
ORDER BY `date` desc
LIMIT 1";
$result3 = $connect->prepare($query3);
$result3->execute();
$row3 = $result3->fetch(PDO::FETCH_ASSOC);
echo json_encode($row3);
As you know which fields you want from the SELECT, it's good to just fetch those fields rather than always using *. This also means that as the result set only contains the fields your after, you can directly json_encode() the result set rather than extracting the fields from one array to another.

FLOT - Fluid / Dynamic Charts - PHP MYSQL

I am trying to Plot a Graph with FLOT but I cant get my head around how to get make it Dynamic with multiple series.
I am trying to get Race Data , Eg Laps and Time as the Graph x and y, but also trying to get the Race ID as a new series line for each Rider.
I have tried it at a Loop for each RaceID, and I have tried it as a multidimensional array, But I cant get my head around how to get it formatted to how FLOT wants it.
I can get it to work with 1 Rider:
$GetLapData = mysql_Query("SELECT LapData.*, u.RaceID
FROM `LapData`
left join User as u on LapData.TagID = u.TagID
Where LapData.EventID = '$EventID'
and LapData.RaceNameID = '$RaceNameID'
and LapData.TagID = '$RacingNumber'
ORDER BY `LapData`.`LapNumber` ASC");
while ($row = mysql_fetch_assoc($GetLapData))
{
$dataset1[] = array($row['LapNumber'],$row['LapTimeinSeconds']);
}
and then plot the single Data Set
$(function() {
var d1 = <?php echo json_encode($dataset1) ?>;
$.plot("#placeholder", [ d1 ]);
});
Any Ideas on making it all riders for the Race would be really helpful.
This is a tough question to answer without seeing your database scheme, but I'll give it a shot.
First, let's modify your SQL statement. I'm guessing that this part and LapData.TagID = '$RacingNumber' is what subset's it down to a single rider? Also, what's the purpose of the join, do you want the rider's name from there or some other identifier? I've left it but if you aren't using it, it's a waste...
$GetLapData = mysql_Query("SELECT LapData.TagID, LapData.LapNumber, LapData.LapTimeInSeconds
FROM LapData
LEFT JOIN User AS u ON LapData.TagID = u.TagID
WHERE LapData.EventID = '$EventID'
ANDLapData.RaceNameID = '$RaceNameID'
AND LapData.TagID = '$RacingNumber'
ORDER BY LapData.TagID, LapData.LapNumber ASC");
$allSeries = array(); // our "return value"
$currentSeries = null; // some temp variables
$currentRider = null;
while ($row = mysql_fetch_assoc($GetLapData))
{
$loopRider = $row['TagID']; // get rider for this database row
if ($currentRider === null || $loopRider != $currentRider) // if first loop or new rider
{
if ($currentSeries !== null)
{
$allSeries[] = $currentSeries; // we have a new rider push the last one to our return array
}
$currentSeries = array(); // this is first loop or new rider, re-init current series
$currentSeries["label"] = $loopRider;
$currentSeries["data"] = array();
}
$currentSeries["data"][] = array($row['LapNumber'],$row['LapTimeinSeconds']); //push row data into object
}
$allSeries[] = $currentSeries; // last rider's data push
In the end, allSeries is an array of associative arrays per flots documentation.
Mainly:
$allSeries = [{
"label" = "tag1",
"data" = [[0,12],[1,45],[2,454]]
},{
"label" = "tag2",
"data" = [[0,122],[1,415],[2,464]]
}]
After you Json encode this, the call is:
$.plot("#placeholder", allSeries);
My Standard PHP disclaimer, I'm not a PHP programmer, I've never used it and never ever want to use it. All the above code was peiced together from quickly reading the documentation and is untested.

Display date once and display results under the respective date. [MySQL/PHP]

$query_ListAbsence = "SELECT count(dated) as dtd, classed, name FROM att group by dtd, classed by dtd desc";
$la = mysql_query($query_la, $sshost) or die(mysql_error());
$row_la = mysql_fetch_assoc($la);
do{
....
}while ($row_la = mysql_fetch_assoc($la));
I want to result to show as
--date--
name1 - classed1
name2 - classed2
--another date---
namea - classeda
nameb - classedb
and so on...
But when inside the do{}while loop the date is displayed the number of times the loop runs. Can i display the results as shown with a single table. This is done by MySQL / PHP.
$arr = array();
while($row = mysql_fetch_assoc($la)) {
$arr[$row['your_date']][] = $row;
}
And than loop through $arr array;

Error printing results from a query that is inside a for loop

I need help on this.
I have to write a query 12 times with just a different value so I did this and it worked fine:
for ($q=1; $q<=11; $q++) {
$ingConcepto[$q] = "SELECT
tbl_ingresos.cantidadpagada AS cp,
tbl_conceingresos.concepto AS concepto,
tbl_ingresos.fechapertenece
FROM
tbl_ingresos
LEFT JOIN
tbl_conceingresos
ON
tbl_ingresos.idtipoingreso = tbl_conceingresos.idingreso
WHERE
MONTH(fechapertenece) = '$q'
AND
YEAR(fechapertenece) = $elcueri1";
$resIC[$q] = mysql_query($ingConcepto[$q],$tewNEW);
$ingConcepto[$q] = mysql_fetch_array($resIC[$q]);
}
The problem comes when I need to print a value it does not display anything:
echo $ingConcepto7['cp'];
Thanks.

Mysql results duplicated even though the query does not match

apologize firstly for my questionable coding in php/mysql however this is all self taught (possibly not best practice)
All my code seems to work , however when the results are written to the page any $dxcall that is not in the $qrzdata database gets filled with the last result all other data displays fine. I have tried changing the like $dxcall to = $dxcall. I have also tried combining the fetch arrays too incase my issues was there too. But clearly my code does not know how to handle where there is not data match in the qrzdata database and to move on.
$frqry is the main data, all the other mysql_query's be it the $squares and $qrzdata are matching what comes from $frqry. Hope this makes sense !!
Here is my code
$frqry = mysql_query("select * from spots where freq between '69900' and '70300' ORDER BY datetime desc limit 30");
While ($r0 = mysql_fetch_array($frqry))
{
$freq = $r0["freq"];
$dxcall = $r0["dxcall"];
$datetime = $r0["datetime"];
$comments = $r0["comments"];
$spotter = $r0["spotter"];
$dt = date('d-m-y H:i ', $datetime);
$qra = $r0["loc"];
$squares = mysql_query("select * from squares where callsign like '$dxcall' limit 1");
while ($r1 = mysql_fetch_array($squares))
{
$qra = $r1["loc"];
}
$qrzdata = mysql_query("select * from qrzdata where callsign = '".$dxcall."' limit 1");
While ($r2 = mysql_fetch_array($qrzdata))
{
$country = $r2["country"];
$firstname = $r2["firstname"];
$city = $r2["city"];
}
Any help is greatly appreciated. Thank you.
You need to learn about the power of the JOIN ;)
Your whole code could be rewritten in one single query :
disclaimer: not tested, but you certainly get the idea
SELECT * FROM spots
JOIN squares ON (squares.callsign = spots.dxcall) -- this comes in stead of your first inner loop
JOIN qrzdata ON (qrzdata.callsign = spots.dxcall) -- this is your second loop
WHERE freq BETWEEN 69900 AND 70300 -- remove quotes, you are dealing with integers, not strings (hopefully)
You have to reset your vars!
While ($r0 = mysql_fetch_array($frqry))
{
$qra = '';
$country = '';
$firstname = '';
$city = '';
or you will allways get the last value

Categories