Pick daily data via SQL query - php

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?

Related

Update multiple rows for 1000 records in one go

I have one table based on which one I have to update 6 rows in the other table for matching ids. It is total of over 1000 records so most of the time I get timeout error with current script.
The way I do it now is, I select the range of ids between two dates from the first table, store it into an array and then run foreach loop making update in the second table where the ids are the same, so basically I run a query for every single id.
Is there anyway I could speed it up the process?
I found only a way to generate the each within the foreach loop
UPDATE product SET price = CASE
WHEN ID = $ID1 THEN $price1
WHEN ID = $ID1 THEN $price2
END
But I don't know how could I modify this to update multiple rows at the same time not just one.
My script code look like that
$sql = "SELECT * FROM `games` where (ev_tstamp >= '".$timestamp1."' and ev_tstamp <= '".$timestamp2."')";
while($row = mysqli_fetch_array($sql1)){
$one_of =[
"fix_id" =>$row['fix_id'],
"t1_res" =>$row['t1_res'],
"t2_res" =>$row['t2_res'],
"ht_res_t1" =>$row['ht_res_t1'],
"ht_res_t2" =>$row['ht_res_t2'],
"y_card_t1" =>$row['y_card_t1'],
"y_card_t2" =>$row['y_card_t2'],
"t1_corners" =>$row['t1_corners'],
"t2_corners" =>$row['t2_corners'],
"red_card_t1" =>$row['red_card_t1'],
"red_card_t2" =>$row['red_card_t2']
];
array_push($today_games,$one_of);
}
foreach($today_games as $key=>$val){
$cards_t1=$val['red_card_t1']+$val['y_card_t1'];
$cards_t2=$val['red_card_t2']+$val['y_card_t2'];
$sql = "Update sights SET t1_res='".$val['t1_res']."',
t2_res='".$val['t2_res']."', ev_tstamp='".$val['ev_tstamp']."',
ht_res_t1='".$val['ht_res_t1']."', ht_res_t2='".$val['ht_res_t2']."',
t1_corners='".$val['t1_corners']."',t2_corners='".$val['t2_corners']."',
t1_cards='".$cards_t1."',t2_cards='".$cards_t2."'
where fix_id='".$val['fix_id']."' "
}
Consider an UPDATE...JOIN query using fix_id as join column. Below runs mysqli parameterized query using timestamps. No loop needed.
$sql = "UPDATE sights s
INNER JOIN `games` g
ON s.fix_id = g.fix_id
AND g.ev_tstamp >= ? and g.ev_tstamp <= ?
SET s.t1_res. = g.t1_res,
s.t2_res. = g.t2_res,
s.ev_tstamp = g.ev_tstamp,
s.ht_res_t1 = g.ht_res_t1,
s.ht_res_t2 = g.ht_res_t2,
s.t1_corners = g.t1_corners,
s.t2_corners = g.t2_corners,
s.t1_cards = (g.red_card_t1 + g.y_card_t1),
s.t2_cards = (g.red_card_t2 + g.y_card_t2)";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $timestamp1, $timestamp2);
mysqli_stmt_execute($stmt);

Echo number of rows where id=$id

I've tried to echo number of rows where a certain id=$id. This is essentially to count the number of "votes" a person has been receiving on the website. It works like a charm in mysqlworkbench, however the number of rows where this person's id has been inserted into database (through the voting button) won't show up on the webpage. The table name is forslag_stemmer, and it has its primary key= id, and foreign keys brukerid (the user that votes for a certain person) and foreign key forslagid (this is the people who receives votes from the users).
This query works in workbench, but not on the page:
echo "<u><b>Number of votes</u></b>:";
$sql= "SELECT COUNT( * ) FROM
bb.forslag_stemmer WHERE forslagid=$forslagid";
$resultat = $kobling->query($sql);
while($rad=$resultat->fetch_assoc())
{
$forslagid = $rad["forslagid"];
echo $sql;
echo "$resultat->num_rows";
}
I really don't know what to do?
You select one field COUNT( * ) as result of your query. There will be no other fields in a result.
echo "<u><b>Number of votes</u></b>:";
// I added an alias for field
$sql= "SELECT COUNT( * ) as votes_count FROM bb.forslag_stemmer WHERE forslagid=$forslagid";
$resultat = $kobling->query($sql);
$rad = $resultat->fetch_assoc();
// access value by alias
echo $rad['votes_count'];
mysqli_result::num_rows Gets the number of rows in a result
In your Example since you're querying as "select count(*) from table" it always returns Number of rows as "1"
You can get Number of rows in two ways
Method 1:
$sql= "SELECT * from FROM bb.forslag_stemmer WHERE forslagid=$forslagid";
$result = $con->query($sql);
echo $result->num_rows; // prints number of rows found
Method 2:
$sql= "SELECT count(*) as resultcount from FROM bb.forslag_stemmer WHERE
forslagid=$forslagid";
$result = $con->query($sql);
while($row = $result->fetch_assoc()){
echo $row['resultcount']; // prints number of rows found
}

SQL Query From multiple table sum column and display

i have a database with 2 different tables
One table (players) contain a column nammed "totaldeplata" that contains numbers (price)
Other table (vanzari) contain a column like the first one nammed "totaldeplata" it hase the same value inside numbers (the price)
i manage to display the sum of all column for each table like this:
<div align="right"> Total Comenzi luna curenta: <i><strong>
<?php
$query = "SELECT * FROM vanzari WHERE MONTH(datainregistrarii) =
MONTH(CURRENT_DATE())";
$query_run = mysql_query($query);
$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
$qty += $num['totaldeplata'];
}
echo $qty;
?></strong> </i> Lei
</div>
But this, display only the sum of one table, so i have to write the same code to display the sum of other column in the secound table (in this case the players table)
I need to sum all the numbers from columns "totaldeplata" from tables: vanzari and players, and display them as one number (to sum all the numbers and display them)
Actualy Sum numbers from columns "totaldeplata" from both tables "vanzari" and "players" and display them.
Any ideea how to do that? :)
SELECT (SELECT SUM(field1) FROM table1) + (SELECT SUM(field2) FROM table2) as result
According to your above code and table name.
<?php
$query = "SELECT (SELECT SUM(totaldeplata) FROM vanzari) + (SELECT SUM(totaldeplata) FROM players) 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;
?>

PHP sum of PHP and MySQL fields echo

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.

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.

Categories