PHP sum of PHP and MySQL fields echo - php

I have a database with the follow tables:
sales
expenses
taxes
earnings
When I sell some product it adds a item to sales, the same to expenses while I add expenses, taxes are added automaticly when selling and earnings too. They are on the same database but different tables.
I need to sum those fields together. I do it one by one without problems like this:
<?php
$query = mysqli_query($db, "SELECT SUM(total) AS `total` FROM `sales`");
while($result = mysqli_fetch_assoc($query)){
echo number_format($result['total'],0,',','.');}
?>
and
<?php
$query2 = mysqli_query($db, "SELECT SUM(expense) AS `expense` FROM `expenses`");
while($result2 = mysqli_fetch_assoc($query2)){
echo number_format($result2['expense'],0,',','.');}
?>
How do I sum those two and echo a result example:
sales - expense = value ?

<?php
$query = mysqli_query($db, "SELECT SUM(total) AS `total` FROM `sales`");
$query2 = mysqli_query($db, "SELECT SUM(expense) AS `expense` FROM `expenses`");
$total_sales = 0;
$total_expenses = 0;
while($result = mysqli_fetch_assoc($query)){
$total_sales = $total_sales + $result['total'];
echo number_format($result['total'],0,',','.');
}
while($result2 = mysqli_fetch_assoc($query2)){
$total_expenses = $total_expenses + $result['total'];
echo number_format($result2['expense'],0,',','.');
}
?>
The sum would be $total_sales-$total_expenses.

Are you sure you will sum those two together?
There are at least good points you do those things separation.
Firstly, the logic is very clearly.
Secondly, if you have many data like those, when you sum them separately, those will not influence each other. Because when you select data and do some operation, if the data is not huge, it will be ok. But if it is huge data, both your database and your cpu and memory will have big pressure.
Thirdly, when you select in database, it is not suggested doing operations such as sum, sub, division and multiplication, although database can do it. Because these operations are really wasting performance of database and computer.
Anyway, you still want to do that. Then you can try to left joint or right joint your table. You can use some foreign keys to connect these two tables and then you can do things which you wanna to do.

Related

Pick daily data via SQL query

I have a problem, I'm trying to make a sum of a daily data from a specific table and column
<?php
$query = "SELECT (SELECT SUM(totaldeplata) FROM vanzari WHERE
MONTH(datainregistrarii) = MONTH(CURRENT_DATE())) + (SELECT SUM(totaldeplata)
FROM players WHERE MONTH(datainregistrarii) = MONTH(CURRENT_DATE())) as result";
$query_run = mysql_query($query);
$row = mysql_fetch_assoc($query_run);
$sum = $row['result'];
echo "sum of two different column from two tables : "+ $sum;
?>
This php query pick the monthly data and make a sum of it, it works, but I want to be able to make also a sum of daily data.
Any idea how?

PHP/SQL How can I make my query include results that has no records in another table yet?

I have 2 php codes that performs room search. The user specifies no. of beds, check in date and check out date. The first code retrieves all rooms with the corresponding number of beds. The second code checks if the room has an existing booking, if it does and the booking dates do not clash with the user input dates the room is displayed, if it does not have an existing booking it is simply displayed.
My first php code:
$sql = "SELECT rooms.rid, beds, orientation, price FROM rooms
WHERE (beds = $nOfBeds)";
if ($rOrientation != "") {
$sql .= " AND orientation = '$rOrientation'";
}
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));
My second php code:
<?php
while ($row = mysqli_fetch_array($results)) {
$sql2 = "SELECT rid, checkin, checkout FROM bookings";
$results2 = mysqli_query($conn, $sql2)
or die ('Problem with query' . mysqli_error($conn));
$row2 = mysqli_fetch_array($results2);
if ($row["rid"] == $row2["rid"]) {
if (($cInDate < $row2["checkin"] && $cOutDate <= $row2["checkin"]) ||
(($cInDate >= $row2["checkout"] && $cOutDate > $row2["checkout"]))) {
?>
<tr>
<td><?php echo $row["rid"]?></td>
<td><?php echo $row["beds"]?></td>
<td><?php echo $row["orientation"]?></td>
<td><?php echo $row["price"]?></td>
</tr>
<?php }
}
} ?>
currently it is working right in regards to filtering out clashing dates however it is also filtering out rooms that does not have an existing booking. another problem i encountered with this code is it does not seem to work for multiple bookings with the same room id (rid) so right now it is only filtering dates regarding the first booking.
this is my booking table: http://imgur.com/DGOko1f
this is rooms table: http://imgur.com/ED5KFES
You can use,
if($result != NULL) {
// Execute code
} else {
// Give NULL values or error
}
Other way is, if(count($result) > 0).
This way you can get error free results.
nanjero05
Several things with the code. In the second php code your are going to execute a query per each room. That is not so good because it will generate many requests to the database.
Also your are requesting ALL the bookings, and then filtering in memory the ones that corresponds to the room. That it is also not always goods. Your read all the bookings again and again per each room.
One solution is to add in the second query (second php code) a condition to select only the bookings for the current room.
$rid = $row["rid"]
$sql2 = "SELECT rid, checkin, checkout FROM bookings where rid = $rid";
(Note: read about SQL injection to improve this)
Then you know that if the $result has no records, there are no bookings for the room.
why you need multiple query try this simple one liner
$sql = "SELECT rooms.rid, beds, orientation, price FROM rooms
WHERE beds = $nOfBeds AND rid NOT IN (SELECT bookings.rid FROM bookings WHERE user_checkin between checkin and checkout or ('user_checkin <= checkin AND user_checkout >= checkout) )";

PHP - how to output a MySQL average store rating in a loop

I have a table with ratings for every store in a directory. I want to display the average rating from each store on a business directory list page. I have the directory business listing page finished without the average rating.
I believe I have figured out how to create an average rating, but I don't know how to get the rating to output in the loop for each store.
Here is how I calculate the rating:
$result = mysql_query("SELECT AVG(rating) FROM reviews GROUP BY store_id WHERE store_id = '$storeid'");
$rating_for_page = mysql_fetch_row($result);
$rating = $rating_for_page[0];
Use the query:
echo "<table>\n";
echo "<tr><th>Store ID</th><th>Name</th><th>Avg. Rating</th></tr>\n";
$result = mysql_query("SELECT s.store_id, s.store_name, AVG(r.rating) AS avg_rating
FROM stores as s
JOIN ratings as r ON s.store_id = r.store_id
GROUP BY s.store_id");
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td>$row[store_id]</td><td>$row[store_name]</td><td>$row[avg_rating]</td></tr>\n";
}
echo "</table>\n";
Then loop through the results of this query. Each row will be the average rating of a different store.
You should iterate through the results if I am understanding the issue correctly. Also, in your MySQL command you need to set an AS for the AVG(rating). And I have set mysql_fetch_assoc (instead of mysql_fetch_row) for the results to be returned in an associative array:
foreach ($storeids as $storeid) {
$result = mysql_query("SELECT AVG(rating) AS rating FROM reviews GROUP BY store_id WHERE store_id = '$storeid'");
while ($row = mysql_fetch_assoc($result)) {
echo $row['rating'];
}
}
EDIT Looking at your query and seeing the $storeid being set, unclear where that value is coming from but I wrapped the solution I have provided in a foreach loop which assumes you have a list—and hopefully an array—that contains all of the $storeids in to loop through.

Running mysql query on php multiple times but with different condition

screenshot: http://i.stack.imgur.com/mX29j.png
im currently making an invoice receipt. the numbers you see on the image, 4600 and 33, are the retrieved values from the checklist from the first page. As you can see, it only lists ONE charge where as it should be two.
this is the part of the code:
$procedures = $_SESSION['receipt'];
foreach($procedures as $key=>$procedureno)
{
$query = "select * from `charges` where `procedure_no` = $procedureno";
echo $procedureno;
$result2=mysql_query($query,$dbh1);
if(mysql_num_rows($result2) > 0 ){
while($row = mysql_fetch_array($result2)){
echo '
<tr>
<td>'.$row[1].'</td>
<td>'.$row[2].'</td>';
echo '</tr>';
}
}
}
I want this query $query = "select * from charges where procedure_no = $procedureno"; to be executed several times depending on how many the $procedureno is.
MySQL understands lists. Try this:
SELECT * FROM charges WHERE procedure_no IN (1, 5, 33, 78)
Create a method and pass the condition as a parameter.
Inside that method put your FOR cycle.

Excluding a variable when its value is blank

The code below works great. I have a MySQL database that contains book titles classified in different categories. In the code below, the variable "site" represents a book title. Each category is represented by a different table in the MySQL database.
The code below ranks the top 25 book titles (site) by total votes across all categories (MySQL tables). I am trying to exclude blank book titles (i. e. when site = ''). How can I do this?
I have tried inserting WHERE site != '' in a few places but I get an error message. So I guess I'm asking, where can I insert WHERE site != ''?
Thanks in advance,
John
<?
mysql_connect("mysqlv10", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$result = mysql_query("SHOW TABLES");
$tables = array();
while ($row = mysql_fetch_assoc($result)) {
$tables[] = '`'.$row["Tables_in_bookfeather"].'`';
}
$subQuery = "SELECT site, votes_up FROM ".implode(" UNION ALL SELECT site, votes_up FROM ",$tables);
// Create one query that gets the data you need
$sqlStr = "SELECT site, sum(votes_up) sumVotesUp
FROM (
".$subQuery." ) subQuery
GROUP BY site ORDER BY sum(votes_up) DESC LIMIT 25";
$result = mysql_query($sqlStr);
$arr = array();
echo "<table class=\"samples2\">";
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td class="sitename2">'.$row["site"].'</td>';
echo '<td>'.$row["sumVotesUp"].'</td>';
echo '</tr>';
}
echo "</table>";
?>
You shouldn't have separate tables for each book category. I can't believe you have so many books that any of these tables would grow too large. Any scalability benefits you might gain by splitting the table are offset by the complexity of having to do these UNION queries.
Here's what I'd do:
Unify the tables into one table.
Add a Categories table.
Relate books to categories with a many-to-many table.
Then your SQL query becomes much simpler:
$sqlStr = "SELECT site, votes_up FROM Books
WHERE site IS NOT NULL AND site <> ''
ORDER BY votes_up DESC LIMIT 25";
It's probably safest to put it in the subquery:
$subQueryParts = array();
foreach($tables as $table)
$subQueryParts[] = "SELECT site, votes_up FROM $table WHERE LENGTH(site)";
$subQuery = implode(" UNION ALL ", $subQueryParts);
If possible, you should follow Bill Karwin's advice and store all your books in one table. Dynamic table names are very hard to search and manage, and they do not optimize well.

Categories