mysql with the date function - php

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 |
+-----------------+

Related

Find lowest date (custom) in mysql

I have no idea how can I find the lowest string in date-type
I will just find lowest month(by years in a table)
TableName
Id | M | D | Y |
=======================
1 | 01 | 22 | 2012 |
2 | 11 | 29 | 2012 |
3 | 12 | 30 | 2013 |
4 | 01 | 30 | 2011 | <--- this !
5 | 12 | 14 | 2012 |
PHP:
$sql = "SELECT * FROM TableName WHERE M=?? AND Y=??";
$selected = mysql_query($sql);
so $selected should give me a result like "4/01/30/2011" (Id,M,D,Y)
Any?
SELECT min(concat(Y,M,D)) FROM TableName
Edit: This just looks nice and clean but it is kind of very bad answer, so please use this answer
Just use the ORDER BY clauses:
SELECT * FROM TableName
ORDER BY Y ASC, M ASC, D ASC
More info here : http://www.tizag.com/mysqlTutorial/mysqlorderby.php
bugwheels94's answer will give you the correct result:
SELECT min(concat(Y,M,D))
FROM `TableName`
but this will be unable to use any index you have on any of the date's constituent fields, so will have to visit every row in the table to determine the minimum value.
Combining m4t1t0 and koopajah's answers gives you:
SELECT *
FROM `TableName`
ORDER BY Y, M, D
LIMIT 1
This will be able to use an available index on Y, and maybe even a combined index on (Y,M,D) which can perform much faster on larger tables.
All this being said; It's almost criminal to put an answer to this question that doesn't suggest using a date field instead of your three column setup. The only reason I can think of to separate a date column would be for performance on niche queries that require separate indexes on day or month, but the choice of accepted answer suggests to me that this isn't the case.
As pointed out by Lucius.. If it's a date, store it as a date and run:
SELECT MIN(`DateColumnName`) FROM `TableName`
As a bonus this will give you access to all the MySQL Temporal functions on the column, including the ability to extract day and month, format it how you like and a single field to index and order by.
Please, do yourself a favour and use a date field instead.. you'll save yourself a lot of troubles.
ALTER TABLE `TableName` ADD `date` DATE NOT NULL;
UPDATE `TableName` SET `date` = CONCAT( `Y` , '-', `M` , '-', `D` );
then you'll be able to do:
SELECT MIN(`date`) FROM `TableName`
Simply perform a query ordering by year, month and day and limit your result to the first row.
SELECT * FROM TableName ORDER BY Y, M, D ASC limit 1;
Try this:
SELECT MIN(ColumnName) FROM TableName;
In your case, that would be:
SELECT MIN(Y) FROM TableName;
I am giving you some idea for your query. Kindly follow that :
$sql="SELECT * FROM tbl_name ORDER BY Y, M, D ASC limit 1;
$res=mysql_query($sql);
$row=mysql_fetch_array($res);
$date=$row["id"]."/".$row["M"]."/".$row["D"]."/".$row["Y"];
echo $date;
I hope It will help you
SELECT concat(Y,M,D) FROM TableName
ORDER BY Y ASC, M ASC, D ASC
Limit 1
That way you can return the whole row by replacing "concat(Y,M,D)" with * and easily adapt for different use cases. You could e.g. return the last date row inside the first year by:
SELECT * FROM TableName
ORDER BY Y ASC, M DESC, D DESC
Limit 1
Storing as DATETIME and using native MySQL sorting speeds it up a lot. If you need to keep the seperate values (for whatever reason, e.g. import/export with other systems out of your scope), maybe you can just add another value to the table and synchronise the values?

Select from all tables with same start

How to select all tables who whas fs_ for example, its not a prefix, its a something added from me , but some tables has it, and i want to select all of them, not choasing the one by one, but to select all tables who starts with fs_
in your MySQL database you can create an extra column that will contain such value.
ex:
ID | NAME | DATE | FS_COLUMN
1 jon 2011 1
2 doe 2005 0
3 tom 2001 1
Then with PHP you can fetch these rows.
$q = mysql_query("SELECT * FROM table WHERE FS_COLUMN='1'");
$r = mysql_fetch_array($q);
$q = $dbc -> ("SELECT COUNT (*) fs_");
$q -> execute();
$count = $q -> rowCount();
echo $count;
It is hard to tell what you are asking or what you are trying to achieve!?
From what you have said try that, if not then please elaborate your question in a more clear and concise way.
well ... it's really no good design approach but to answer your question:
you will probably want to get all matching tables by
SELECT table_name
FROM information_schema.tables
WHERE table_schema = '___YOUR_DB_NAME___'
AND table_name LIKE 'fa\_%'
and construct your query based on the result

mysql query show only 1 result

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.

mysql collection of visitor days?

I have a mysql table - table1. It has ID (autoinc), dt (datetime), name (varchar) columns. When a visitor visits they can enter their name in the database. On some days their are no visitors.
From this, i'm trying to find if their is some way to make a list in php of all days for which their was at least 1 visitor.
Any ideas?
Select distinct date(dt) from table1
So then, in php you would do something like:
$result = mysql_query("select distinct date(dt) from table1");
while($row = mysql_fetch_array($result)){
echo $row[0] . "\n";
}
This would print each date on a different line.
Should give you a list of the unique dates that data was written to the table.
Updated to use date() instead of day()
*Updated to fix the missing parenthesis *
To extract only those dates.
SELECT DATE_FORMAT(dt, '%Y-%m-%d') AS the_date,
COUNT(*) AS visitors
FROM table
GROUP BY the_date
HAVING visitors > 0;

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