mysql query show only 1 result - php

i want to output the result based on todays date.
the problem is, the output only show 1 result?
database report table:
id | r_amount | id_therapist | date | time | t_tanning | t_deep
// this query works fine echoing all the result if i use while loop
$today = date('Y-m-d');
(1) $q = $db->query("SELECT * FROM report WHERE date='$today' ORDER BY date ASC")
// this query only show 1 output result?
(2) $q = $db->query("SELECT *, SUM(IF(t_tanning LIKE 'Pro Tan%', r_amount, 0)) AS totalProTan FROM report WHERE date='$today' ORDER BY date ASC")
while($r = $q->fetch_array(MYSQLI_ASSOC)) :
// (1) echoing all result from database
echo $r['r_amount'].'<br>';
// (2) echoing only 1 result????
echo $r['totalProTan'].'<br>';
endwhile;

If the date field is of type datetime, you'll have to do something like
SELECT ... WHERE DATE(date)=CURDATE()
Notice that I'm using curdate() in the query. There's no need to generate the date value in PHP. MySQL is perfectly capable of doing that itself.

Try adding a GROUP BY statement to the second SQL statement.
you should group by the key of the elemnts you want to be shown in the end result

The use of the aggregate function SUM will result in a single result. You are asking the database to get all the rows then sum up a value and give you the value.
To see the result for many groups of values you have to add a group by clause.

Related

mysql, use condition in "where"

I have a database table like:
id name date price
1 a 2014-05-12 10
2 a 0000-00-00 20
3 a 2014-05-13 30
I want to search by date, and if the date exists, return the price of the date.
if the date does not exist, return the price of date 0000-00-00.
For example:
search by date:2014-05-12, return `10`
search by date:2014-05-20, return `30`
I have tried:
select price from table where (date=table.date or table.date='0000-00-00')
but it does not work.
How do I write the correct query?
Here is one method that uses order by and limit:
select t.price
from table t
where t.date in ('0000-00-00', #date)
order by t.date desc
limit 1;
Note that I changed the parameter name from date to #date to distinguish it from the column with the same name.
The syntax should table table.field (e.g. table.date), while in your example you have field.field (price.date).
Try:
select price from table where (table.date='{$date}' or table.date='0000-00-00')
Note that $date is a variable (assuming you use PHP). If you don't use PHP, you can't just write date as a variable here, but you can use #date.
Get the value of the field to be searched.Let it be $date_search.
if(!empty($date_search)) {
$sql = 'select price from table where date ='.$date_search;
mysql_query($sql);
}
else {
$sql = 'select price from table where date ="0000-00-00"';
mysql_query($sql);
}

What is the returned result from a SELECT MAX() when table is empty in MySQL?

I have a table for users payments. I need to specify a receipt code for each transaction, so I need to know what was the last one? And if there is not previous receipt, I want to add the first one with 1000 and other reciepts must be incremental like 1001, 1002, ...
For this, I wrote this code:
$receipt = '1000';
$query_receipt = mysql_query("SELECT MAX(receipt) FROM tbl_payments");
$max = mysql_result($query_receipt,0);
if ($max != '0' || $max != '')
{
$receipt = mysql_result($query_receipt,0) + 1;
}
It works fine when I have a record in the table. But it returns 1 when table is empty. How can I solve this problem? I need to know the returned value from a SELECT MAX() ... even if table be empty.
You can achive this by using IFNULL as:
SELECT IFNULL(MAX(receipt), 1000) FROM tbl_payments;
You get a null value:
mysql> create table noRows (id int(3));
Query OK, 0 rows affected (0.03 sec)
mysql> select max(id) from noRows;
+---------+
| max(id) |
+---------+
| NULL |
+---------+
1 row in set (0.00 sec)
You can however use a coalesce to get what you need:
mysql> select coalesce(max(id),1) from noRows;
+---------------------+
| coalesce(max(id),1) |
+---------------------+
| 1 |
+---------------------+
1 row in set (0.01 sec)
Edit: If you are looking to check it the user already has one and if not, to insert a new row, it can't be done with a single query as far as I know, but the following should work:
$receipt = 1000;
$query_receipt = mysql_query("SELECT MAX(receipt) FROM tbl_payments");
$num_rows = mysql_num_rows($query_receipt);
if($num_rows>0)
{
// Assumes $ID to be some unique field used to identify your customer stored in field ID.
$sql="insert into tbl_payments (ID, receipt) values ($ID, $receipt)";
mysql_result($sql)
}
else
{
// Do stuff here to get the receipt from the first resultset.
}
On that note, you might want to consider moving away from the old deprecated mysql_* functions and move to PDO instead. It is much safer and has a lot more features.
I'd also recommend, to use an auto_increment value, and determine your current receipt number by the insert_id. Simply execute your INSERT-Query and afterwards use for example mysqli_insert_id to get the id of your inserted payment.
If you want to start with a value of 1000, you can change the start value of your auto increment column. I found this to set up auto increment to start with 1000
ALTER TABLE tbl_name AUTO_INCREMENT = 1000
The below should work as your insert statement. No need to use PHP to run two queries as above, you can do the same outcome direct in MYSQL.
INSERT INTO tbl_payments (receipt)
VALUES
(
(SELECT CASE WHEN MAX(p.receipt) IS NULL THEN 1000 ELSE MAX(p.receipt)+1 END AS receipt
FROM tbl_payments p ORDER BY p.receipt DESC LIMIT 1)
)

mysql with the date function

I have a mysql table containing a field name dtt_date and have values like
08/04/2010 22:15:00. I want to display all the records with in this month (08, august), How to write a mysql query in my php page to display these record.
Does any one know this?
Please help me?
SELECT * FROM table WHERE dtt_date>='2010-08-01' AND dtt_date<='2010-08-31';
In PHP:
$q = "SELECT * FROM table WHERE dtt_date>='2010-08-01' AND dtt_date<='2010-08-31'";
$res = mysql_query($q);
while($row = mysql_fetch_assoc($res))
var_dump($row);
mysql_free_results($res);
Untested, I'm sure there are easier methods to this. Not sure if your date format will be handeled by MySQL
SELECT * FROM table WHERE MONTH(DATE_FORMAT(date,'%Y-%m-%d')) = 8
You can try this one method
SELECT * FROM table WHERE month(dtt_date)='08' AND year=(dtt_date)='2010';
You should change the date format in the table to be '2010-08-04 22:15:00', then you could run this query:
SELECT DATE_FORMAT(dtt_date, '%D %M %Y') as date FROM myTable
From there you would get something of this as a result, and then you can experiment with the date formatting.
+-----------------+
| date |
+-----------------+
| 4th August 2010 |
+-----------------+

How to use DATEDIFF? How many days are inside of two dates

How to use DATEDIFF? How can I make this to work? or should I use DATEDIFF completly differently?
SELECT DATEDIFF('Started ','will_end') AS 'Duration' FROM my_table WHERE id = '110';
I try to get answer, how many days are inside of two dates.
I would like to get an aswer like:
Duration = 7 days;
I have this kind of database:
Started | will_end
2009-12-17 | 2009-12-24
2009-12-12 | 2009-12-26
Put will_end first, started second:
SELECT DATEDIFF('2009-12-24', '2009-12-17')
---
7
Also, remove the single quotes from your field names:
SELECT DATEDIFF(will_end, started) AS Duration
FROM my_table
WHERE id = 110
, or replace them with the backticks:
SELECT DATEDIFF(`will_end`, `started`) AS `Duration`
FROM `my_table`
WHERE `id` = 110
Are you getting a NULL result? You have the column names in single quotes in your query, which means you are passing the strings 'Started ' and 'will_end' to DATEDIFF rather than the column values. Try removing the single quotes, and you will start to see some results:
SELECT DATEDIFF(Started, will_end) AS Duration FROM my_table WHERE id = '110';
Note that this will give you a negative result. To get a positive result, reverse the order of the columns:
SELECT DATEDIFF(will_end, Started) AS Duration FROM my_table WHERE id = '110';
replace the order
DATEDIFF('will_end','Started')
I think there are 3 parameter to be passed in
DATEDIFF ( datepart , startdate , enddate )
so your code would be
DATEDIFF ( dd , 'Started ','will_end' )
http://msdn.microsoft.com/en-us/library/ms189794.aspx

Sql results into php array

I would like to create an array (in php) from sql results like this:
We have the sql-table "Posts" which stores the Name and the Message.Example:
Name | Message
John | Hello
Nick | nice day
George | Good bye
John | where
What i want is to output the names of people who have posted a message but dont display the same names more than 1 time.
So the output would be John,Nick,George.
(From these records, we see that John has posted 2 messages, but at the final output, we see only one time his name).
Is this somehow possible?
Thanks in advance.
Try:
$sql = <<<END
SELECT DISTINCT Name FROM Posts
END;
$query = mysql_query($sql) or die($sql . ' - ' . mysql_error());
$names = array();
while ($row = mysql_fetch_array($query)) {
$names[] = $row[0];
}
print_r($names);
SELECT DISTINCT
You could run a SQL query to just select the distinct names, and nothing else:
SELECT DISTINCT Name FROM Posts;
This will give you a result set consisting of distinct Names values, with each unique value only being returned 1 time in the set.
to get the count you will need to aggregate using group by:
SELECT
NAME
, COUNT(*) as Posts
FROM
Posts
GROUP BY
NAME
Here is the SQL if you are not averse to group BY
select count(name) as N, name from posts group by name ;
People having more than 1 post
select count(name) as N, name from posts group by name having N > 1 ;

Categories