Add all values together SQL SELECT - php

How do I add all the amounts together so that instead of this select script returning all the individual withdrawal amounts return one number of them all added together?
<?php
$end_date = strtotime($nextdate);
$start_date = strtotime($statement_date);
$username = $usr['username'];
$result = mysql_query("SELECT * FROM `usr_withdraw` WHERE `timestamp` > '$start_date' AND `timestamp` < '$end_date' AND `username` = '$username'")or die(mysql_error());
while($balance = mysql_fetch_array( $result )) {
echo $balance['amount'];
}
?>

To return only 1 row with the aggregate sum of all amounts use the sql sum() function.
SELECT sum(amount) FROM `usr_withdraw` WHERE ...

Do
$result = mysql_query("SELECT SUM(amount) FROM `usr_withdraw` WHERE `timestamp` > '$start_date' AND `timestamp` < '$end_date' AND `username` = '$username'")or die(mysql_error());
But also keep in mind that these mysql_* functions are out of PHP from version 7 on, then your code will be soon out of date. The ideal is using mysqli_* functions or PDO.

Related

MySQL/PHP - Display Recent Date

I was able to apply this line onto phpMyAdmin and it worked just fine.
SELECT id, date_format(`date`, '%m.%d.%Y') as `date` FROM TABLE ORDER BY date DESC LIMIT 1
The problem is that when I added the rest of the code, the recent date shows up blank on the webpage. Am I missing something in this code?
<?php
$query = "SELECT id, date_format(`date`, '%m.%d.%Y') as `date` FROM TABLE ORDER BY date DESC LIMIT 1";
$result = mysql_query($query);
echo "$date";
?>
Any help is appreciated. Thank you.
. Try this
$query = "SELECT id, date_format(`date`, '%m.%d.%Y') as `date` FROM TABLE ORDER BY. date DESC LIMIT 1";
$result = mysql_query($query);
$r = mysql_fetch_assoc($result);
$date = $r['date'];
echo "$date";
You didn't set $date variable. You need to use mysql_fetch_array function for your $result variable.
Ex:
`
$query = "SELECT id, date_format('date', '%m.%d.%Y') as 'date' FROM TABLE ORDER BY date DESC LIMIT 1";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row); }
`

Previous record in MySql

In my table i have date records like 02-04-2016 , 03-01-2016 and 04-01-2016 if i am on 03-01-2016 i want the previous record which is 02-01-2016 But it gives me 01-01-2016 which is the first record of my table. No matter what date i am on.
if(isset($_POST['place'])){
$place = $_POST['place'];
$date = date("Y-m-d", strtotime($_POST['date']));
$classtype = $_POST['classtype'];
$getdate = mysql_query("SELECT * FROM `class` WHERE `city`='$place' AND `clastype`='$classtype' AND `classdate`<'$date' limit 0,1")or die(mysql_error());
$mydt = mysql_fetch_array($getdate);
$mdt = date("d-m-Y", strtotime($mydt[classdate]));
echo $mdt;
}
"SELECT * FROM `class` WHERE `city`='$place' AND `clastype`='$classtype' AND `classdate`<'$date' order by `classdate` desc limit 0,1"
Please use order by clause.
Use ORDER BY clause
Try this:
SELECT *
FROM `class`
WHERE `city`='$place' AND `clastype`='$classtype' AND
`classdate`<'$date'
ORDER BY id DESC
LIMIT 0,1

else mysql query to take up the first 20 dates

I have a sql query which has an if..else function. if the submit button is clicked, it will perform the particular query. else, the query will take in the first 20 dates in my database. however, i am not sure how to do the else query statement to take up only the first 20 dates. do help, thank you :)
<?php
$server = "localhost";
$user = "root";
$password = "";
$database = "sensors_database";
$connection = mysql_connect($server,$user,$password);
$db = mysql_select_db($database,$connection);
if(isset($_POST["usub"])){
$date1 = $_POST["datepicker"];
$date2 = $_POST["datepicker1"];
$query1 = "SELECT time, Ultrasonic FROM pi_sensors_network WHERE date BETWEEN '".$date1."' AND '".$date2."'";
$result1 = mysql_query($query1);
while($row = mysql_fetch_assoc($result1))
{
$dataset1[] = array(strtotime($row['time'])*1000,$row['Ultrasonic']);
//echo strtotime($row['time'])*1000;
}
}
else {
}
?>
Here you go:
SELECT `time`, `Ultrasonic` FROM `pi_sensors_network`
WHERE 1=1 ORDER BY `date` ASC LIMIT 0,20
If you are asking between the dates you mentioned in the query, then use
limit
$query1 = "SELECT time, Ultrasonic FROM pi_sensors_network WHERE date BETWEEN '".$date1."' AND '".$date2."' limit 0,20";
First Create index on table < pi_sensors_network > on column < date >
CREATE INDEX pi_sensors_network01 ON pi_sensors_network (`date`);
Then,
SELECT
`time`,`Ultrasonic`
FROM
pi_sensors_network
WHERE
`date` IN ( SELECT `date` FROM
(SELECT DISTINCT(`date`)
FROM pi_sensors_network
ORDER BY `date` ASC LIMIT 0,20)
AS tmp ) ;
If your table is too large, This query may take long even after indexing,
In this case,
I'ld suggest you to make an array of first 20 dates by separate query and then implode it in your main query !

PHP - How to Use ORDER BY and GROUP BY together

I created a table that contains message, sender, to, time I want group by sender and order by time this is my code
$query= mysql_query("SELECT * FROM `table` ORDER BY `time` GROUP BY `sender`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr ['message'];
echo '</br>';
echo $msg;
}
that shows me this error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BYsender' at line 1
So how to fix that problem?
Thanks
Klaus
Note your precedence. After the results have been grouped , it should be ordered.
"SELECT * FROM `table` GROUP BY `sender` ORDER BY `time`"
try this code
$query= mysql_query("SELECT * FROM `table` GROUP BY `sender` ORDER BY `time` ")or die(mysql_error());
// ^^--will be before order
$num = mysql_num_rows($query); // out of the while loop
while($arr = mysql_fetch_array($query)){
$msg = $arr['message'].'<br />';
// ^^--remove space here
echo $msg;
}
how to use self-joins to get the max/min/something-n rows per group.
In your situation, it can be applied to the effect you want like so:
SELECT * FROM
(SELECT group_id, MAX(`yourdate`) AS yourdate FROM tbl_name GROUP BY group_id)
AS x JOIN tbl_name USING (`group_id`,yourdate);

PHP For Loop through date range not working

I'm trying to loop through every day in a month and get the number of results for each day in one month.
I've done the following;
<?php
include 'inclues/db.inc.php';
for($i = 2; $i < 30; $i++){
$date2 = $i-1;
$date1 = $i;
$q = mysql_query("SELECT * FROM `table` WHERE `date` < '2012-09-".$date1." 00:00:00' AND `date` > '2012-09-".$date2." 00:00:00'";
//$r = mysql_fetch_assoc($q);
echo mysql_num_rows($q)."<br />";
}
?>
It works if I just try to echo out dates 1 and 2 but not if I use the query.. I end up with a 500 internal server error when using the query.
Any ideas on how to resolve this? Is it generally bad practice to use a query within a loop?
Just execute
SELECT date, COUNT(*) from table group by date
SELECT * FROM `table` WHERE `date` BETWEEN $date1 AND $date2;
It's not bad practice to use a query within a loop.
Check what your query-string is becomming, try running that query manually on your db. It probably produses some error.
$sql = "SELECT * FROM `table` WHERE `date` < '2012-09-".$date1." 00:00:00' AND `date` > '2012-09-".$date2." 00:00:00'";
echo $sql;
$q = mysql_query($sql);

Categories