PHP Mysql COUNT results in a double loop - php

I would like to know how can I count the results in case I have two loop ! :
$select = "SELECT X FROM Y"
$result = mysql_query($select,$link);
$total = mysql_num_rows($result);
while($row = mysql_fetch_array($result)) {
$Name = $row['X'];
$select2 = "SELECT id FROM `".$Name."` ";
$result2 = mysql_query($select2,$link) or die ('Erreur : '.mysql_error() );
$total2 = mysql_num_rows($result2);
while($row2 = mysql_fetch_array($result2)) { echo $row2['id']} }
I would like to count how many id I have at the end . Thanks for your help

just give this
$select = "SELECT X FROM Y"
$result = mysql_query($select,$link);
$total = mysql_num_rows($result);
$finalTotal=0;
while($row = mysql_fetch_array($result)) {
$Name = $row['X'];
$select2 = "SELECT id FROM `".$Name."` ";
$result2 = mysql_query($select2,$link) or die ('Erreur : '.mysql_error() );
$total2 = mysql_num_rows($result2);
$finalTotal = $finalTotal + $total2;
while($row2 = mysql_fetch_array($result2)) { echo $row2['id'];} }
echo "total id is ".$finalTotal;
$finalTotal will show you total number of id's

Related

How to add values to in the result of while loop in php

How to add the result of the while loop which is stored on the variable $profit? results are 5 and 70
the code
<?php
$sql2 = "SELECT * from `products`";
$result2 = $link->query($sql2);
while($row2 = $result2->fetch_assoc())
{
$sql3 = "SELECT * from `orders` where product_id = '".$row2['prod_id']."'";
$result3 = $link->query($sql3);
$row3 = $result3->fetch_assoc();
$sql = "SELECT SUM(product_qty) from orders where product_id = '".$row2['prod_id']."'";
$result = $link->query($sql);
$row = mysqli_fetch_array($result);
$res = bcmul($row2['prod_price'], $row[0]);
$profit = $res - $row2['prod_cost'];
if($row[0] == null){
$row[0] = 0;
}
}?>
Try this code
<?php
$sql2 = "SELECT * from `products`";
$result2 = $link->query($sql2);
$totalProfit = 0;
while($row2 = $result2->fetch_assoc())
{
$sql3 = "SELECT * from `orders` where product_id = '".$row2['prod_id']."'";
$result3 = $link->query($sql3);
$row3 = $result3->fetch_assoc();
$sql = "SELECT SUM(product_qty) from orders where product_id = '".$row2['prod_id']."'";
$result = $link->query($sql);
$row = mysqli_fetch_array($result);
$res = bcmul($row2['prod_price'], $row[0]);
$profit = $res - $row2['prod_cost'];
$totalProfit = $totalProfit + $profit
if($row[0] == null){
$row[0] = 0;
}
}?>
now you can use $totalProfit variable value as total.

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;
}

Multiple mysqli select with json

<?php
include"../database_conn.php";
$con=mysqli_connect("localhost","admin","123456","ayurveadic");
$query_pag_data = "SELECT id from diseases";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());
while ($row = mysql_fetch_array($result_pag_data)) {
$diseases_id = $row['id'];
$result = mysqli_query($con,"SELECT $diseases_id FROM treatment WHERE gender_id = '10' AND diseases_id = '$diseases_id'");
$row_gid = mysqli_fetch_array($result);
if ($row_gid == TRUE){
$sl_dise = mysqli_query($con,"SELECT Diseases_type, id FROM diseases WHERE id = '$diseases_id'");
$rowss = array();
while($r = mysqli_fetch_assoc($sl_dise)) {
$rowss[] = $r;
}
print json_encode($rowss);
}
}
Output is:
[{"Diseases_type":"fever","id":"114"}][{"Diseases_type":"rhrh","id":"123"}]
How can i get this output:
[{"Diseases_type":"fever","id":"114"},{"Diseases_type":"rhrh","id":"123"}]
You need to initialize the JSON array before the outer loop, and print it at the very end, not each time through.
<?php
include"../database_conn.php";
$con=mysqli_connect("localhost","admin","123456","ayurveadic");
$query_pag_data = "SELECT id from diseases";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());
$rowss = array();
while ($row = mysql_fetch_array($result_pag_data)) {
$diseases_id = $row['id'];
$result = mysqli_query($con,"SELECT $diseases_id FROM treatment WHERE gender_id = '10' AND diseases_id = '$diseases_id'");
$row_gid = mysqli_fetch_array($result);
if ($row_gid == TRUE){
$sl_dise = mysqli_query($con,"SELECT Diseases_type, id FROM diseases WHERE id = '$diseases_id'");
while($r = mysqli_fetch_assoc($sl_dise)) {
$rowss[] = $r;
}
}
}
print json_encode($rowss);
Here is you optimised code
<?php
include"../database_conn.php";
$con=mysqli_connect("localhost","admin","123456","ayurveadic");
$query_pag_data = "select diseases.Diseases_type,diseases.id from diseases inner join treatment on treatment.diseases_id = diseases.id where treatment.gender_id = '10' ";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());
$rowss = array();
while ($row = mysqli_fetch_assoc($result_pag_data)) {
$rowss[] = $row;
}
print json_encode($rowss);
?>
Put your
print json_encode($rowss);
after end of thiswhile ($row = mysql_fetch_array($result_pag_data)) {
Also remove this $rowss = array(); array initialization

SQL query not showing more than 1 row

This is the entire code the error must be in query 3 or 4. As you can see query 3 just gets info to build query 4 which should return the results.
I've got query 1 & 2 working ok which have the correct data showing.
<?php
session_start();
//printf('<pre>%s</pre>', print_r($_SESSION, true));
require('includes/config.inc.php');
require('includes/session.php');
//WORKING
DB_Connect();
$query = "SELECT * FROM food_delivery_orders_items WHERE food_delivery_orders_items.type = 'product' AND food_delivery_orders_items.order_id=".$_SESSION['pdf_quote']['id']."";
$result = mysql_query( $query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$hash = $row['hash'];
$foreignid = $row['foreign_id'];
$qty = $row['cnt'];
}
$query2 = "SELECT * FROM food_delivery_products WHERE food_delivery_products.id = ".$foreignid."";
$result2 = mysql_query( $query2) or die(mysql_error());
while($row = mysql_fetch_array($result2))
{
$name = $row['name'];
$description = $row['description'];
}
//---------------------------------------------------------------------------------------------------------------
$query3 = "SELECT * FROM food_delivery_orders_items WHERE food_delivery_orders_items.type = 'extra' AND food_delivery_orders_items.order_id=".$_SESSION['pdf_quote']['id']."";
$result3 = mysql_query( $query3)or die(mysql_error()) ;
while($row = mysql_fetch_array($result3))
{
$foreignidextra = $row['foreign_id'];
$qtyextra = $row['cnt'];
}
$query4 = "SELECT * FROM food_delivery_extras WHERE food_delivery_extras.id = ".$foreignidextra."";
$result4 = mysql_query( $query4) or die(mysql_error());
while($row = mysql_fetch_array($result4))
{
$nameextra = $row['name'];
}
echo $nameextra;
echo $qtyextra;
DB_Disconnect();
//$products = implode(", ",$_SESSION['pdf_quote']['product_arr']);;
//print $products
?>
print $row; is only valid inside the loop if you want to print all of them. Otherwise it will print only the last $row. Make it
while($row = mysql_fetch_array($result3))
{
$foreignidextra = $row['foreign_id'];
$qtyextra = $row['cnt'];
print $row;
}
its because you are printing the $row after the while loop gets executed
So it only prints the final result set
Use something like this instead:
$query3 = "SELECT * FROM food_delivery_orders_items WHERE food_delivery_orders_items.type = 'extra' AND food_delivery_orders_items.order_id=".$_SESSION['pdf_quote']['id']."";
$result3 = mysql_query( $query3) ;
while($row = mysql_fetch_array($result3))
{
$foreignidextra = $row['foreign_id'];
$qtyextra = $row['cnt'];
print_r($row);
}
you can also use the var_dump($row); instead of print_r($row);
this will output all the values stored in the $row array each time the loop iterates

Display message in PHP when the result of mysql query has no value

I have a table in PHP which displays the result of the MySQL query.
The database table item_em has the price details of the items that are available in hypermarkets available in the database table hypermarket_em.There are some items that aren't available in the hypermarket. Hence when i display the prices in the table I want those cells with no price as N/A.
So my problem is I tried a code myself to display message when database table field has no value.But it doesn't work and I don't get any error as well. Any ideas much appreciated. Thank you.
Here is my code
$res = mysql_query("SELECT h_id FROM hypermarket_em") or die(mysql_error());
echo"<tbody><tr>";
while($row = mysql_fetch_array( $res ))
{
$result = mysql_query("SELECT item_name FROM items_em WHERE h_id=".$row['h_id'])or die(mysql_error());
while($drop_4 = mysql_fetch_array( $result ))
{
echo"<th scope=row>".$drop_4['item_name']."</th>";
$rslt = mysql_query("SELECT price FROM items_em WHERE item_name='".$drop_4['item_name']."' and h_id=".$row['h_id'])or die(mysql_error());
if (mysql_num_rows($rslt) == 0)
echo"<td>N/A</td>";
while($drop = mysql_fetch_array( $rslt ))
{
echo"<td>".$drop['price']."</td>";
}
}
}
echo"</tr></tbody>";
Try reversing your mysql_num_rows and check if you have > than 0 rows-
if (mysql_num_rows($rslt) > 0){
while($drop = mysql_fetch_array( $rslt )){
echo"<td>".$drop['price']."</td>";}
}
else{
echo"<td>N/A</td>";}
Edit-
I think what you are wanting to do then is something like this-
while($drop = mysql_fetch_array( $rslt )){
if ($drop['price'] == ''){
echo"<td>N/A</td>";}
else{
echo"<td>".$drop['price']."</td>";}
$data = mysql_fetch_array( $res );
if (!empty($data)) {
while($row = mysql_fetch_array( $res ))
{
$result = mysql_query("SELECT item_name FROM items_em WHERE h_id=".$row['h_id'])or die(mysql_error());
while($drop_4 = mysql_fetch_array( $result ))
{
echo"<th scope=row>".$drop_4['item_name']."</th>";
$rslt = mysql_query("SELECT price FROM items_em WHERE item_name='".$drop_4['item_name']."' and h_id=".$row['h_id'])or die(mysql_error());
if (mysql_num_rows($rslt) == 0)
echo"<td>N/A</td>";
while($drop = mysql_fetch_array( $rslt ))
{
echo"<td>".$drop['price']."</td>";
}
}
}
} else {
echo "<td>No record found</td>";
}
Not really sure what you're trying to do here, but it seems like you might want to simplify your query as well. Try something like:
SELECT
*
FROM
hypermarket_em h
LEFT JOIN items_em i ON ( h.h_id = i.h_id );
Using this query, you can do something like:
while($drop = mysql_fetch_array( $rslt )){
echo"<td>" . ( empty( $drop['price'] ) ? 'N/A' : $drop['price'] ) . "</td>";
}
So here is my answer.
$res = mysql_query("SELECT DISTINCT h_id FROM hypermarket_em") or die(mysql_error());
echo"<tbody><tr>";
while($row = mysql_fetch_array( $res ))
{
$result = mysql_query("SELECT item_name FROM items_em WHERE h_id=".$row['h_id'])or die(mysql_error());
while($drop_4 = mysql_fetch_array( $result ))
{
echo"<th scope=row>".$drop_4['item_name']."</th>";
$rslt = mysql_query("SELECT price FROM items_em WHERE item_name='".$drop_4['item_name']."' and h_id=".$row['h_id'])or die(mysql_error());
while($drop = mysql_fetch_array( $rslt ))
{
echo"<td>".$drop['price']."</td>";
}
}
}
$res = mysql_query("SELECT DISTINCT h_id FROM hypermarket_em") or die(mysql_error());
while($row = mysql_fetch_array( $res ))
{
$result = mysql_query("SELECT item_name FROM items_em WHERE h_id=".$row['h_id'])or die(mysql_error());
if(mysql_num_rows($result)<=0)
echo"<td>N/A</td>";
}
echo"</tr></tbody>";
I had to execute the same query twice as i want the item names and the price values in the order. So I first print the item names and then only the prices or "N/A" message.
Thank you all for your help..:)

Categories