Iterating Through PHP Array for Chart Display - php

I'm having trouble iterating through a PHP array in order to display a chart. Right now, my code is only resulting in the display of one column in the chart (this column is displaying correctly), but I can't seem to get other columns to display.
This is my code right now (in a php section at the top of my html page). I know that the issue is with this section of code, because the chart is rendering perfectly, but just not adding a column for each record in the table.
I'd really appreciate any insight into the mistakes I'm making here. Thank you.
$valueAnimalType = $_POST['animaltype'];
$connect = mysqli_connect("127.0.0.1","____","_____",3306);
$result = mysqli_query($connect,"SELECT * FROM DISPOSAL");
$datas = array();
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$datas[] = $row;
}
foreach ($datas as $data){
$datas = array(
array('y' => $data[$valueAnimalType], "label" => $data['DisposalName'] ));
}
}

modify your code here:
foreach ($datas as $data) {
//LINE BELOW
$datas [] =
array('y' => $data[$valueAnimalType], "label" => $data['DisposalName']);
//LINE ABOVE
}
you're overwriting your $datas each time loop passes with last record, now it's appending new item to array

Related

foreach array wise multi SQL query not working in PHP

I am trying to execute multiple queries with the multiple selected checkbox value-wise in PHP.
I am facing trouble that my code is executing only one checkbox value-wise query and the rest is denied.
I checked on StackOverflow about this issue and I got lots of threads about foreach loop but in my case, it is not working when I am applying that.
Please help me, I am first time trying the foreach loop and so that I have a bit confusing about the same.
I have also the problem that I am not able not to validate invalid data through an array.
How I fix this? it only works for the first check value but I want all checked checkboxes.
I am trying to fetch data from the database of those particular ids which value I selected in the checkbox. and echo it in the array for that all query as I mention below-
Sending Form Data format as seen in dev tool
referenceID[]: PO0203211
referenceID[]: PO203213
PHP
$checkbox = $_POST['referenceID'];
foreach ($checkbox as $chk) {
$stmt = $con->prepare(
"SELECT * FROM `table` WHERE `ref` = :referenceid"
);
$stmt->execute([':referenceid' => $chk]);
$stmt = $stmt->fetchAll();
$response = [];
$i = 1;
foreach ($stmt as $data) {
$response[] = [
"slno" => $i,
"name" => $data['name'],
"orderid" => $data['address'],
];
$i++;
}
echo json_encode($response);
exit();
}
Try this, when using exit() inside the foreach the code does not continue and only performs the first element.
EDIT 1:
Ok, I'm going to explain a little more in depth how to optimize this code.
You get "id" identifiers from checked checkboxes.
You can use SQL IN () to optimize this.
Look at this
$checkboxDivide = implode("','", $_POST['referenceID']);
$response = []; //Final Result
$stmt = [];
$query = mysqli_query($con,
"SELECT * FROM `table` WHERE `ref` IN('{$checkboxDivide}')"
);
while($stmt[] = mysqli_fetch_assoc($query));
//Delete empty last array
array_pop($stmt);
$i = 1;
foreach ($stmt as $data) {
$response[] = [
"slno" => $i,
"name" => $data['name'],
"orderid" => $data['address'],
];
$i++;
}
echo json_encode($response);
You're using the exit() function withing your foreach, which will terminate the current script. See php manual on exit.
I am referencing to the
foreach ($checkbox as $chk) {}
not to the
foreach ($stmt as $data) {}
The script will terminate after the first loop of the first foreach.
Try moving it out of the foreach.
**Updated answer because of the comment from #El_vanja
Move your $response = []; array above and out of the foreach loop. This will keep the data in the array and not reset the array every iteration of the foreach loop.

PHP - Multidimensional Array

I am basically trying to fetch results from a SQL database and load that into a multidimensional array so i can use them later on in the page.
while($row = mysqli_fetch_array($result))
{
$send = array
(
array($row['Name'],$row['Email'],$row['Mobile'])
);
$count = $count + 1;
}
That is what i am using to get the results which if i print within the while loop it will echo all the results. However when putting it into the array it loads each result into the array as the first result. My initial plan was to use a counting variable to set where in the array the result was set to with this adding by one each time. I am not certain how to specify where to add the result i thought something along the lines of
$send = array[$count]
(
array.....
so i could then refer to the results as 0 to count length but i am not sure how to make this work. Or ,which i presume, if there is a much easier and better way of going about it. I am also not sure if this is necessary as surely the results seem to be in an array when gathered from the SQL database but i am unsure if this array is populated with each while loop or stored and can be accessed at any point
If any one can give me an example of something similar or point me at some documentation much appreciated
Try this:
$count = 0;
while ($row = mysqli_fetch_array($result)) {
$send[$count] = array($row['Name'], $row['Email'], $row['Mobile']);
$count++;
}
I have a better way for you. You could also use the id for your index, if you have one:
while ($row = mysqli_fetch_array($result)) {
$send[$row['id']] = array(
"Name" => $row['Name'],
"Email" => $row['Email'],
"Mobile" => $row['Mobile']
);
}
You can use:
$count = 0;
while($row = mysqli_fetch_array($result))
{
$send[$count] = $row;
$count ++;
}
Also you might want to use the table id as an array index, so you can access the records by ID later. In that case you can do:
while($row = mysqli_fetch_array($result))
{
$send[$row['id']] = $row;
}
You're declaring your array inside your loop. So it will reset it every time.
$send = array();
while($row = mysqli_fetch_array($result))
{
$send[] = array($row['Name'],$row['Email'],$row['Mobile']);
}

Check $row for value and amend

I am using flexigrid for displaying data and need help to check a row for a value and change it. The data is being returned to flexigrid via json and works well and without ant errors. however, what I am trying to do is check the row; $row['status'] for a value = 1 and if that row is that value then change it to value = "In".
I have tried various ways to code using an if statement, but it does not error, just dosen't display the data in the grid. What is the correct way to code this row? Thanks
$results = mysql_query($sql);
while ($row = mysql_fetch_assoc($results)) {
$data['rows'][] = array(
'id' => $row['Id'],
'cell' => array($row['Id'], $row['rack'].$row['column'].'-'.$row['row'].'-'.$row['bay'], $row['customer'], $dropdown, $service, $row['department'], if ($row['status']==1){$row['status']="In"}, $row['custref'], $row['size'], $row['authorisation'], date('d/m/Y H:m:s',strtotime($row['intake_date'])), date('d/m/Y',strtotime($row['destroy_date']))));
}
echo $json->encode($data);

Adding items to a multi-dimensional array during query while loop

I have a query returning data that looks like this:
Status Total
Success 234
Failed 20
Missing 12
I want to add this to an array which can then be used to populate a google pie chart.
the array would look like this:
array backup = array("Success" => 234),
("Failed" => 20),
("Missing" => 12);
How would I add these item dynamically at each row in a query?
$result = mysql_query(...);
$backup = array();
while ($r = mysql_fetch_assoc($result)) {
$backup[$r['Status']] = $r['Total'];
}
Here's how you can make the Google Charts API call:
$values = implode(',', array_values($backup));
$labels = implode('|', array_keys($backup));
$img = "http://chart.apis.google.com/chart?cht=p3&chd=t:{$values}&chl={$labels}&chs=250x100";
echo "<img src='{$img}' alt='Chart'>";
Assuming this is your query:
SELECT status, total FROM table
Then you can do:
$data = array();
while(($row = mysql_fetch_assoc($result))) {
$data[$row['status']] = $row['total'];
}
If this is not what you mean, please clarify your question and/or provide the code you already have.
I think we need a bunch more information, but in the mean time look at array_merge()
http://www.php.net/manual/en/function.array-merge.php

Adding to a multidimensional array in PHP

I have an array being returned from the database that looks like so:
$data = array(201 => array('description' => blah, 'hours' => 0),
222 => array('description' => feh, 'hours' => 0);
In the next bit of code, I'm using a foreach and checking the for the key in another table. If the next query returns data, I want to update the 'hours' value in that key's array with a new hours value:
foreach ($data as $row => $value){
$query = $db->query('SELECT * FROM t WHERE id=$row');
if ($result){
$value['hours'] = $result['hours'];
}
It's all fine except that I've tried just about every combination of declarations for the foreach loop, but I keep getting the error that the $value['hours'] is an invalid reference. I've tried declaring $value[] ... but that doesn't work either. I don't need to iterate through $value so another foreach loop isn't necessary.
Surely this is easier than my brain is perceiving it.
Here's the whole snippet:
foreach($_gspec as $key => $value){
$sql = sprintf('SELECT * FROM List WHERE specialtyID=%s', $key);
$query = $db->query($sql);
if ($query->num_rows() !== 0){
$result = $query->row_array();
$value['hours'] = $result['hours'];
}
}
You want
$data[$row]['hours'] = $result['hours']
$row would be better named as $key (that is what it is!)
Some people would suggest using pointers, but I find this way makes more sense to me.
You need to use ampersand in front of the $value in foreach to pass it by reference like this:
foreach ($data as $row => &$value){
$query = $db->query($sql);
if ($result){
$value['hours'] = $result['hours'];
}
}
More info here: http://php.net/manual/en/control-structures.foreach.php
As of PHP 5, you can easily modify
array's elements by preceding $value
with &. This will assign reference
instead of copying the value.
Use reference ->
foreach ($data as $row => & $value) {
$query = $db->query('SELECT * FROM t WHERE id=$row');
// [...]
if ($result) {
$value['hours'] = $result['hours'];
}
}

Categories