Why is my array empty after looping? - php

I'm trying to write some code that gets random prices from a database until a specific amount is reached. I want it to add the name and price to an array and then print it at the end with $total_items, but it's only showing the last item. What's wrong?
$total = 0;
while ( $total <= $amount ) {
$query = "SELECT name, price FROM table ORDER BY RAND() LIMIT 1";
$run_query = mysql_query($query);
$total_items = array();
while($row = mysql_fetch_assoc($run_query)) {
$total_items[] = $row;
echo $row['name'] . ' / ' . $row['price'] . "<br>";
$total = $total + $row['price'];
}
}
echo "<br>" . Total Amount: ".$total;
print_r($total_items);

variable $total_items is defined in the while loop, so it is truncated in every while loop, and $total_items will only keep the last result.
try to put it above while ( $total <= $amount )

Please define $total_items outside the while loop. And double quote properly to print the output.
$total = 0;
$total_items = array();
while ( $total <= $amount ){
$query = "SELECT name, price FROM table ORDER BY RAND() LIMIT 1";
$run_query = mysql_query($query);
while($row = mysql_fetch_assoc($run_query)) {
$total_items[] = $row;
echo $row['name'] . ' / ' . $row['price'] . "<br>";
$total = $total + $row['price'];
}
} echo '<pre>';echo "Total Amount: ".$total; print_r($total_items);`

Related

Outputting values from a loop resulting in value of zero

I am currently trying to output the value of an array using a for loop.
I have tried outputting the query that is running in the loop (Resulting in an echo of 24 queries)
1
$number_of_beams = 24;
for ($i = 0; $i < $number_of_beams; $i++)
{
$query = "SELECT fitacf_data.time,
SUM(fitacf_data.num_pts) AS point_total
FROM
fitacf_data
WHERE abbrev = '" . $radar_array[0]['radar_abbrev'] ."'
AND fitacf_data.beam = '" . $i . "'
GROUP BY fitacf_data.time";
$result = pg_query($query) or die('Error: ' . pg_last_error());
while ($row = pg_fetch_array($result)) {
$beam_total_array[] = $row;
}
echo $i
echo $beam_total_array[0]['point_total'] . "<br><br>";
}
If I hard code $i to any value from 0-23 echo $beam_total_array[0]['point_total']; outputs the correct value 24 times.
ie:
2
for ($i = 0; $i < $number_of_beams; $i++)
{
$query = "SELECT fitacf_data.time,
SUM(fitacf_data.num_pts) AS point_total
FROM
fitacf_data
WHERE abbrev = '" . $radar_array[0]['radar_abbrev'] ."'
AND fitacf_data.beam = '5'
GROUP BY fitacf_data.time";
$result = pg_query($query) or die('Error: ' . pg_last_error());
while ($row = pg_fetch_array($result)) {
$beam_total_array[] = $row;
}
echo $i
echo $beam_total_array[0]['point_total'] . "<br><br>";
}
$i is returning 0-23 as expected.
If I run the code as shown in #1 using the $i variable the output is 0 for the 24 times.
What am I missing here?
The problem is that you're declaring $i as a string, which has a value of 0. Remove the double quotes around $i: AND fitacf_data.beam = ' . $i . '

how to get count(*) the right way in php

I tried to count() the data from database with php but it don't show me the total data but it show the datas.
this is how I count
$query = "SELECT
mitra.*,
user.username,
user.privilege,
user.name
FROM
mitra
INNER JOIN
user ON mitra.id_user = user.id "
$result = $connection->query($query);
if ($result->num_rows > 0) {
foreach ($result as $row) :
$id = "" . $row["id"] . "";
$total = "" . $row["total_puas"] . "";
$privilege = "" . $row["privilege"] . "";
if ($privilege == 2) :
$calculate = $total / count($id);
var_dump(count($id));
endif;
endforeach;
}
===================
= id = total =
= 1 = 45.84 =
= 2 = 75.45 =
= 3 = 34.54 =
===================
when I var_dumb it it shows int(1)int(1)int(1) not int(3) that what I wanted.
actually I want to count $calculate with the data in $total that should be there is float and the amount from $total that I want to divided with count id
is there any solution that how to count the amount from $total and can be devided with count $id that should be 3?. please help
what I really trying to do from that table example is like 45.84 + 75.45 + 34.54 / 3
Sounds like you want a COUNT() with GROUP BY in your query. Doing count($id) in PHP will always yield one, as its not an array of values.
$query = "SELECT COUNT(id) as cnt, id, total_puas
FROM table
GROUP BY id";
$result = $connection->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$calculate = $row["total_puas"] / $row['cnt'];
echo $row['id']." has a count of ".$row['cnt'].", a total of ".$row['total_puas']." and calculated to ".$calculate."<br />\n";
}
}
From your updated question, the output becomes a bit more clear. Based on the output data and the result you desire, you want to calculate the sum of all total_paus, divided by the number of rows. You can do this directly in one query, like this
$query = "SELECT SUM(total_puas) / COUNT(u.id) as total
FROM mitra AS m
INNER JOIN user AS u
ON mitra.id_user = user.id";
$result = $connection->query($query);
$row = $result->fetch_assoc();
$total = $row['total'];
echo $total;
You can try this code:
<?php
$i = 0;
$total =0.00;
if ($result->num_rows > 0) {
while ($row = $result->fetch_array()):
if ($row["privilege"] == 2) :
$total = $total + $row["total"];
$i++;
endif;
endwhile;
echo $total."<br>";
echo $i."<br>";
echo $calculate = $total / $i;
}
?>
output
=====================================
$total = 155.83;
$i = 3;
$calculate = $total/$i;
$ans = 51.943333333333;
=====================================
You can try this code:
$query = "SELECT * FROM table"
$result = $connection->query($query);
if ($result->num_rows > 0) {
$total = 0.0;
foreach ($result as $row) :
$id = "" . $row["id"] . "";
$total = $total + $row['total'];
endforeach;
$calculate = $total / $result->num_rows;
echo $total.<br>;
echo $calclulate;
}

give a unique number from 1 to 200 for each row? assign a number for each row

I have this small code to display 200 rows and I want to give each row a number a per the no of votes.
How can I do it?
This is what I thought of but it does not work.
$sql = 'SELECT * FROM table LIMIT 200;
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$row = 1;
echo $row++;
echo $row['fullname'];
echo '<br>';
}
the output is making all row output to 1.
edit :
okay so some of the answers did the job but it does not work on the pagination. it counts from 1 on page 2,3,4,5.... heres the code.
<?php
$sql = "SELECT * FROM table";
$result = mysqli_query($conn, $sql);
$result_per_page = 20;
$no_of_result = mysqli_num_rows($result);
$no_of_page = ceil($no_of_result/$result_per_page);
if(!isset($_GET['page'])){
$page = 1;
}else{
$page = $_GET['page'];
}
$page_first = ($page-1)*$result_per_page;
$sql = 'SELECT * FROM table LIMIT ' . $page_first . ',' . $result_per_page;
$result = mysqli_query($conn, $sql);
$num = 1;
while($row = mysqli_fetch_assoc($result)) {
echo $num++;
echo $row['fullname'];
echo '<br>';
}
for($page=1;$page<=$no_of_page;$page++){
echo ''.$page.'';
echo ' ';
}
?>
Try to read your code line by line and see what it does.
while($row = mysqli_fetch_assoc($result)) { # > Set variable $row to the next result set or exit when there are none.
$row = 1; # Set variable $row to value 1.
echo $row++; # Increment variable $row to + 1.
echo $row['fullname']; # Row is now an integer, not an array. (You did that 2 statements ago)
echo '<br>'; #
} // end of loop, start again --------------|
A solution would be:
$id = 1;
while($row = mysqli_fetch_assoc($result)) {
echo $id++;
echo $row['fullname'];
echo '<br>';
}
As for the page, you're overwriting the previous value:
for($s=$page;$s<=$no_of_page;$s++){
echo ''.$s.'';
echo ' ';
}

Average of horizontals data mysql php

I hope you are doing well. I am working in a school management project , i want to get the average of 5 test(devoir) of each subject(Matiere) like-
i tried to use AVG() inside while loop of getting horizontale devoir data, i got no result ,any suggestions ??
$query5 = "select * from devoir where CIN_ELEVE = '$cinE' and ID_ELV_AN_CLS = $select2 GROUP BY MODULE_DEVOIR";
$result5 = mysqli_query($con,$query5);
if(mysqli_num_rows($result5)>0)
{
echo"<table class='table table-bordered table-striped table-hover table-info'><tr>
<th>MATIERE</th>
<th>devoir1</th>
<th>devoir2</th>
<th>devoir3</th>
<th>devoir4</th>
<th>devoir5</th>
<th>AVG</th>
</tr>
";
while($rows = mysqli_fetch_assoc($result5))
{
$moduleD = $rows['MODULE_DEVOIR'];
$queryDEV = "select * from devoir inner join eleve on devoir.CIN_ELEVE = eleve.CIN_ELEVE where eleve.CIN_ELEVE = '$cinE' and MODULE_DEVOIR = '$moduleD' order by MODULE_DEVOIR";
$resultDEV = mysqli_query($con,$queryDEV);
/*to print subject name*/
echo"<tr><td>$moduleD</td>";
while($rows = mysqli_fetch_assoc($resultDEV))/*loop2*/
{
$noteDEV = $rows['NOTE_DEVOIR'];
/*to print subject mark(note)*/
echo"<td>$noteDEV</td>";
/*i add the query of average inside the loop to be with touch by all row data mark*/
$queryAVG="select avg($noteDEV) as average_devoir from devoir where MODULE_DEVOIR = '$moduleD' group by MODULE_DEVOIR ";
}
$resultAVG = mysqli_query($con,$queryAVG);
if($rows = mysqli_fetch_assoc($resultAVG))
{
if($rows = mysqli_fetch_assoc($resultAVG))
{
$avg = $rows['average_devoir'];
echo"<td>$avh</td>";
}
}
echo"</tr>";
}
echo"</table>";
}
If you are not required to use SQL to calculate the average, then doing this seems a better option.
while($rows = mysqli_fetch_assoc($result5))
{
$moduleD = $rows['MODULE_DEVOIR'];
$queryDEV = "SELECT * FROM devoir INNER JOIN eleve " .
"ON devoir.CIN_ELEVE = eleve.CIN_ELEVE " .
"WHERE eleve.CIN_ELEVE = '$cinE' " .
"AND MODULE_DEVOIR = '$moduleD' " .
"ORDER BY MODULE_DEVOIR";
$resultDEV = mysqli_query($con,$queryDEV);
/*to print subject name*/
echo"<tr><td>$moduleD</td>";
// We will use this variable to store the sum
$sum = 0;
// And this is a counter to store the number of results
$count = 0;
while($rows = mysqli_fetch_assoc($resultDEV))/*loop2*/
{
$noteDEV = $rows['NOTE_DEVOIR'];
/*to print subject mark(note)*/
echo"<td>$noteDEV</td>";
// Update the sum
$sum += $noteDEV;
// Update the counter
$count ++;
}
// Calculate and display the average
$avg = $sum / $count;
echo "<td>$avh</td>" . "</tr>";
}
If you know that the number of results is always constant, and equals 5, you can get rid of the $count variable and divide by 5 directly.
You may also wish to format the output to fit your needs.

foreach doesn't look like working properly in php

I used following code to get the total price, but it outputs value that is higher than the expected value. What would be the reason for this?
$query = " SELECT *
FROM `mytable`
WHERE `sale_id` = $id";
$result = mysql_query($query);
$item = mysql_fetch_array($result);
foreach ($item as $row) {
$total_price += $row['price'];
}
echo $total_price;
Try this,
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$total_price += $row['price'];
}
echo $total_price;

Categories