Filling a two dimensional array with mysql fetch results in php - php

I just had a framework for creating charts and this is how it works normally.
$p = new chartphp();
$p->data = array(array(
array("A",2),
array("B",3),
array("C",23),
array("D",10)
));
$p->chart_type = "bar";
// Common Options
$p->xlabel = "My X Axis";
$p->ylabel = "My Y Axis";
$out = $p->render('c1');
This way it works perfectly fine, now I need to get results from a sql query and fill the array.
$query ="SELECT t.date AS dates,COUNT(t.id) AS trans FROM Gab AS g, Transaction AS t WHERE t.date BETWEEN '2015-07-30' AND '201-07-10' AND g.TID = '1401009' ORDER BY DATES";
$ask = mysql_query($query) or die("Error");
//Now I try to load the results into the array to be integrated into the API.
$p = new chartphp();
$p->data = array(array(
while($recon = mysql_fetch_array($ask)
{
array($recon['dates'],recon['trans']),
}
));
$p->chart_type = "bar";
// Common Options
$p->xlabel = "My X Axis";
$p->ylabel = "My Y Axis";
$out = $p->render('c1');
I tried this but it does not work, the array dont seem to be loaded !

I'm actually not sure what nesting a while like you have would do and I'm unable to experiment at the moment, but something like this should get you in the right direction:
$p->data = array(array());
while($recon = mysql_fetch_array($ask))
{
$p->data[0][] = array($recon['dates'], $recon['trans']);
}
Initializing the array and then appending the elements in the loop.

Related

Property [associated_occupation] does not exist on this collection instance. - Laravel

I would like to store a database value into the variable. For some reason It's not working as expected. Below is the code in controller:
public function show(Word $word)
{
//
$curriculum = Curriculum::findOrFail($word->id);
// dd($curriculum->id);
session(['key' => $curriculum->id]);
$knowledge = Knowledge::where('curriculum_id','=', $word->id)->get();
$information = Information::where('curriculum_id','=', $word->id)->get();
$practical = Practical::where('curriculum_id','=',$word->id)->get();
$work = Work::where('curriculum_id','=',$word->id)->get();
$entry = Entry::where('curriculum_id','=',$word->id)->get();
$assessment = Assessment::where('curriculum_id','=',$word->id)->get();
$parts = Part::where('curriculum_id','=',$word->id)->get();
$occupurpose = Occupurpose::where('curriculum_id','=',$word->id)->get();
$occutask = Occutask::where('curriculum_id','=',$word->id)->get();
$taskdetail = Taskdetail::where('curriculum_id','=',$word->id)->get();
$purposekm = Purposekm::where('curriculum_id','=',$word->id)->get();
$guidedtopic = Guidetopic::where('curriculum_id','=',$word->id)->get();
$purposepms = Purposepm::where('curriculum_id','=',$word->id)->get();
$purposewem = Purposewem::where('curriculum_id','=',$word->id)->get();
$guidedpmstopics = Guidedpmstopic::where('curriculum_id','=',$word->id)->get();
$guidedwemstopics = Guidedwemstopic::where('curriculum_id','=',$word->id)->get();
$wordTest = new \PhpOffice\PhpWord\PhpWord();
$newSection = $wordTest->addSection();
$SectionHeading = "SECTION 1: CURRICULUM SUMMARY";
$newSection->addText($SectionHeading);
$topicHeading = "1. Occupational Information";
$newSection->addText($topicHeading);
$subTopic = "1.1 Associated Occupation";
$newSection->addText($subTopic);
$newSection->addText($knowledge->associated_occupation);
$occupationTopic = "1.2 Occupation or Specialisation Addressed by this Curriculum";
$newSection->addText($occupationTopic);
$newSection->addText($knowledge->specialisation);
$alternativeTopic = "1.3 Alternative Titles used by Industry";
$newSection->addText($alternativeTopic);
$newSection->addText($knowledge->alternative_title);
$objectWriter = \PhpOffice\PhpWord\IOFactory::createWriter($wordTest,'Word2007');
try {
$objectWriter->save(storage_path('TestWordFile.docx'));
} catch(Exception $e) {
}
return response()->download(storage_path('TestWordFile.docx'));
}
When I do dd of the curriculum id and the knowledge result I get correct feedback. Now I would like to store the column
associated_occupation
into the variable called newSection but I get the error mentioned on the subject. I also tried
$newSection->addText($knowledge->select('associated_occupation')); instead of $newSection->addText($knowledge->associated_occupation);
Please assist.
You are trying to access a property of a collection:
$knowledge = Knowledge::where('curriculum_id','=', $word->id)->get();
The above will give you a collection of results that have the curriculum_id as $word->id
https://laravel.com/docs/5.6/queries#retrieving-results
The get method returns an Illuminate\Support\Collection containing the results where each result is an instance of the PHP StdClass object.
So when you do:
$newSection->addText($knowledge->associated_occupation);
The $knowledge->associated_occupation is looking for associated_occupation on a collection of results rather than a specific Knowledge
Change your query to:
$knowledge = Knowledge::where('curriculum_id','=', $word->id)->first();
To get the first Knowledge that has it's curriculum_id as $word->id
https://laravel.com/docs/5.6/queries#retrieving-results
If you just need to retrieve a single row from the database table, you
may use the first method. This method will return a single StdClass
object:
Or filter the collection and pick a specific one

change the output of the php query result as array

I have a PHP code which has the following output:
[{"stockdata":29655.88482666}]
And I need to change the code on my php to get the result in this format:
[{"data": [29655.88482666]}]
This is the code of my php:
<?php
function getArraySQL(){
$startd = "29964";
$endd = "29968";
$dsn = "prueba";
$connect = odbc_connect( $dsn, '', '' );
$query = "
Select SUM(TON_DESCARGADO) as stockdata
from
(Select unit,[load],enum_LOAD.[name],SUM(dumptons) as TON_DESCARGADO
from hist_dumps inner join hist_loclist on hist_dumps.shiftindex = hist_loclist.shiftindex
and hist_dumps.loc = hist_loclist.locid
inner join enum_LOAD on hist_dumps.[load] = enum_LOAD.[num]
where hist_dumps.shiftindex between '$startd' and '$endd'
GROUP BY loc,UNIT,unit#,[load],enum_LOAD.[name])TEMP1
where unit = 'Stockpile'
GROUP BY unit
order BY UNIT";
if(!$rs = odbc_exec($connect, $query)) die();
$rawdata = array();
$i=0;
while($row = odbc_fetch_array($rs))
{
$rawdata[$i] = $row;
$i++;
}
odbc_close( $connect );
return $rawdata;
};
$stockdata = getArraySQL();
echo json_encode(($stockdata), JSON_NUMERIC_CHECK);
What need to be changed to get the correct format? Should I do something to improve the code of my php?
How should I write it if I connect php to SQL server via PDO and get the same result? (just an optional doubt)
I don't find custom output in json_encode, so if you want to customize the output of array , you would need to prepare it.
I assumed the data exists at zero index (0).
So, I use $stockdata[0]
for JSON_NUMERIC_CHECK replace, used (float)
here is the preparation of output to send exactly you want.
$stockdata = getArraySQL();
$Numeric_data = (float) $stockdata[0];
$data = '[{"data": ['.$Numeric_data.']}]';
echo $data;
Demo

Output data from mysql to array json driving me crazy

im trying to pull out a menu in this json format :
check the output : http://www.alacarta.do/iphone/webservices/restaurants_menu2.php?r=415
The thing is that iterating of the Category plates, it duplicates the plates and then add the corresponding correct ones in each Category. all the time. check the output in the link. first category is TO SHARE. and the plates are ok, but the second category FRIES BAR, will throw again the plates from TO SHARE and then the correct plates in its category
<?
$where = empty($_GET['r'])? NULL : 'id = '. intval($_GET['r']);
$restaurant = $cmp->empresas($where,"nombre ASC")->fetch();
$json = array();
$arraynombre = array();
while($orden = $cmp->platos_tipos_orden("id_empresa = {$restaurant->id}","orden ASC")->foreachrow()):
$tipo = $cmp->platos_tipos("id = {$orden->id_tipo}")->fetch();
while($menu = $cmp->platos_menu("id_tipo = {$orden->id_tipo} AND id_empresa = {$orden->id_empresa}")->foreachrow()):
$p = $cmp->platos_lista("id = {$menu->id_plato}")->fetch();
$pnombre = $p->nombre;
$pid = $p->id;
$pprecio = $p->precio;
$arraynombre1 = array('plato_id'=>$pid,'plato_nombre'=>$pnombre,'precio'=>$pprecio);
if (in_array($arraynombre1['plato_id'], $arraynombre['plato_id'])) continue;
$arraynombre[] = $arraynombre1;
endwhile;
$jsondata = array('tipo'=> utf8_decode($tipo->nombre),'platos' => $arraynombre);
$json[] = $jsondata;
endwhile;
echo json_encode( array("menu"=>$json));
?>
Your issue is probably this line -
$arraynombre[] = $arraynombre1;
as you continually add to the array, not overwrite the previous loops values.
Try adding a key to it that is unique to each loop, ie. $orden->id_tipo -
$arraynombre[$orden->id_tipo][] = $arraynombre1;
Then you would also need to change
$jsondata = array('tipo'=> utf8_decode($tipo->nombre),'platos' => $arraynombre);
to
$jsondata = array('tipo'=> utf8_decode($tipo->nombre),'platos' => $arraynombre[$orden->id_tipo]);
note- it is hard to follow all your code logic, so [$orden->id_tipo] might need to be [$orden->id_empresa] or could be a similar counter var [$x] that you increase on each loop.

extracting values from Mysql query

i am confused about how to extract values from a query, and place them into specific variable, when i don't know before hand what the name of the value will be.
it might be easier to show you what i mean.
the images below are the returned values, grouped by heading i.e Total_responded, Percent_responded etc.
so the first row will have under the column Responce the value Poached with a Percent_responded of 16.66667.
however the next row will have under column Responce $scrambled with a Percent_responded of 83.333333
i now want to place each of these values into individual variables like:
$poached , $poachedPercentage, $scrambled, $scrambledPercentage etc
i attempted to do it below, but produced the wrong figures. this is also not a cost effective way to do it. so, i would really appricaite some advice on how to extract the values
$getPollResult = results();
while ($row = mysqli_fetch_array ($getResult , MYSQLI_ASSOC))
{
$responce = safe_output(round($row['RESPONCE']));
$percentage = safe_output(round($row['Percent_responded']));
if($responce = 'Poached')
{
$percentageOne = $percentage;
$poached = $responce;
}
if ($responce = 'Scrambled')
{
$percentageTwo = $percentage;
$scrambled = $responce;
}
// echo " $percentagePoached $percentageScrambled ";die();
}
Use
$responce = trim($row['RESPONCE']);
Instead Of
$responce = safe_output(round($row['RESPONCE']));
Also, Change in if condition = to ==.
you can use "variable variables" (PHP Docs) to achieve that:
while ($row = mysqli_fetch_array ($getResult , MYSQLI_ASSOC))
{
$responce_name = trim($row['RESPONCE']);
$percentage_name = $responce_name . "Percentage";
$percentage = safe_output(round($row['Percent_responded'])); //don't know what safe_output() does
$$percentage_name = $percentage; //notice the double "$" here
}
your PHP variables will then look like this:
$PoachedPercentage = 17;
$ScrambledPercentage = 83;
// and so on....

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.

Categories