MySQL SELECT rows between two values - php

I need to select data from a mysql database from the past 12 months based on the current date. I have the dates saved in the database as unix timestamps but my query does not seem to work.
$query="SELECT user_id, COUNT(first_name) AS member_count
FROM main_user
WHERE renew_date<'$time' AND renew_date>'$old_time' WHERE renew_date!=''";
Basically I need to count all instances of first_name where there is a renew_date timestamp.

You have an additional WHERE where you should use AND:
$query="SELECT user_id, COUNT(first_name) AS member_count
FROM main_user
WHERE renew_date<'$time' AND renew_date>'$old_time' AND renew_date!=''";
^^^

You have an error in your query, you have two WHERE clauses!

You can find this and other errors, when you test the return value from your query
$query = 'select ...';
$result = $mysqli->query($query);
if ($result === false) {
// error handling
echo $mysqli->error;
} else {
// query successful
// process result set
}

You put WHERE twice. You can use From_UNIXTIME function in mysql
WHERE FROM_UNIXTIME(renew_date)<NOW()
AND FROM_UNIXTIME(renew_date)> (NOW()-INTERVAL 1 year)
AND renew_date !=''

Related

I don't get any result when executing a SQL sentence where I use TRUNC in the WHERE clause in PHP

I have a table in an Oracle database called reservation that has a datetime column called date_reservation. And I have the following code:
$sql = "SELECT COUNT(*) AS numberrows FROM reservation WHERE TRUNC(date_reservation)=TO_DATE('15/06/2015', 'dd/mm/yyyy')";
$stid = $this->bd->execute($sql);
$row = $this->bd->get_row($stid, 0);
echo $row['NUMBERROWS'];
The table content is:
ID ... DATE_RESERVATION
1 13/06/2015 12:00:00
2 ... 15/06/2015 09:00:00
3 ... 15/06/2015 11:00:00
When I execute my PHP code I get 0, and I should get 2.
But if I execute this sql sentence in my DB admin tool I get 2.
If I remove the WHERE CLAUSE from my code ($sql = SELECT COUNT(*) AS numberrows FROM reservation) I get the number of rows in the reservation table.
So I guess something is wrong with TRUNC in PHP. How could I solve it?
It seems you miss a semicolumn at the line 1 :
$sql = SELECT COUNT(*) AS numberrows FROM reservation WHERE TRUNC(date)=TO_DATE('15/06/2015', 'dd/mm/yyyy');
$stid = $this->bd->execute($sql);
$row = $this->bd->get_row($stid, 0);
echo $row['NUMBERROWS'];
Maybe it came from that? :)
You have colons missing in first line:
$sql = "SELECT COUNT(*) AS numberrows FROM reservation WHERE TRUNC(date)=TO_DATE('15/06/2015', 'dd/mm/yyyy')";
$stid = $this->bd->execute($sql);
$row = $this->bd->get_row($stid, 0);
echo $row['NUMBERROWS'];
Try this now. If you still did not get accurate results than check your date format that you are using in query.
The first thing you must pay attention,what comes from trunc(date). Check the data in your date column, the format of date type must be exactly right with the format of to_date('15/06/2015','dd/mm/yyyy')

Displaying amount of users on a webpage

I am trying to write a PHP script that will count the amount of users that have visited the page within the last 10 minutes. This is my script right now:
function getOnlineUsers($database, $main_connection){
$database;
$visitor_id = session_id();
$timestamp = time();
$timeOut = $timestamp - 6000;
mysql_query("INSERT INTO online (m_time, ip) VALUES ('$timestamp', '$visitor_id')", $main_connection);
mysql_query("DELETE FROM online WHERE m_time < $timeOut");
$result = mysql_query("SELECT * FROM online");
mysql_fetch_assoc($result);
if(!$result){
$online_users = 1;
}else{
$online_users = mysql_num_rows($result);
}
return $online_users+1;
}
The problem is that nothing is being inserted into the database and the database remains empty and therefore the count is null. Can someone please assist me in this?
First, better use PDO or MySQLi. In your database, the 'm_time' column must be integer type, and pass the $timestamp value as number, not within quotes.
"INSERT INTO online (m_time, ip) VALUES ($timestamp, '$visitor_id')"
1) Change '$timestamp' to NOW(), mysql can't understand php's time() function ( assuming m_time is a datetime field) .
ie:
INSERT INTO online (m_time, ip)
VALUES ( NOW(), '$visitor_id')
2) Your delete suffers the same problem
3) You can use something a little more clever to get the users in the last 10 minutes, try something like:
select count(*) AS OnlineUserCount
from online
WHERE
m_time > DATE_SUB( NOW(), INTERVAL 10 MINUTE ) ;
Your code looks fine .. what i suggest you do is echo out the query when it runs and cope and paste it and run it directly from phpmyadmin and check if it gives you any error and if the row is inserted succesfully i suggest you check your connection file with the database.
And also try what's suggested by CoursesWeb

mySQL Select DISTINCT ips based on dates and return dates

I am doing this query to know the count of unique IPs by date.
The fact is that I need to return in PHP not only the number of unique IPs by date, but also the dates itself.
How can I do it?
function getTotUniqueVisitsDay($id) {
$query="SELECT COUNT(DISTINCT user_ip) FROM campaigns_visitors WHERE campaign_id = ".$id." group by date";
$result = mysql_query($query) or die("Getting tot unique visits by day failed: " . mysql_error());
$visits_by_day = mysql_num_rows($result);
return $visits_by_day;
}
Your query is
SELECT COUNT(DISTINCT user_ip)
FROM campaigns_visitors
WHERE campaign_id = ?
GROUP BY date
This doesn't return date as you have found.
You should have more luck with
SELECT COUNT(DISTINCT user_ip), date
FROM campaigns_visitors
WHERE campaign_id = ?
GROUP BY date
Others are likely to recomment that you use prepared statements and mysqli routines; I have helpfully translated your query to a format that can be prepared.
I trust you can construct the PHP to manipulate the changed statement.
The best practise is to store the date as last_updated and date_created column. This post suggest how to get update date for any table
How can I tell when a MySQL table was last updated?
and according to following post you can't get update date for specific row in a table
How to get the date of record updating in MySQL
function getTotUniqueVisitsDay($id) {
$query="SELECT date_field FROM campaigns_visitors WHERE campaign_id = ".$id." group by date_field";
$result = mysql_query($query) or die("Getting tot unique visits by day failed: " . mysql_error());
$visits_by_day = mysql_num_rows($result);
$visits_by_day['count'] = count($visits_by_day);
return $visits_by_day;
}

Looping out mysql data

I have a mysql database of entries with dates. So what I want is to show all the dates in my database and then under each date, I want to show all the entries in the database entered on the specefic date. I am thinking of two loops but I don't know how to write the condition to display all the dates in my database before I loop out the entries under that date.
Edit: i used NOW() to store the date. Using the loop by longneck, how can ignore the time when checking if date is sameas previous? Should I explode? What's the best way?
you should use one query, sort it by date, and detect the change in the date as a signal to display the next date:
<?php
$sql = 'select start_date, name from events order by start_date';
$res = mysql_query($sql) or die(mysql_error());
$prev_date = null;
while ($row = mysql_fetch_assoc($res)) {
if ($row['start_date'] != $prev_date) {
echo "<h1>{$row['start_date']}</h1>"\n;
$prev_date = $row['start_Date'];
}
echo "<p>{$row['name']}</p>";
}
?>
I'm assuming that you want a list of the dates so that you can then do separate queries for each date's entries. Usually you would use a query like:
SELECT DISTINCT date_field FROM table_name ORDER BY date_field DESC
(this will do it newest-first, remove DESC to make it oldest-first)
Now, you probably don't want to do it this way, because it will require a lot of queries (one for each day's entries). It is more efficient to just order the entries by the date, and then use logic in your php to print out the headers. So you would use code like:
$result = $db->query("SELECT * FROM table_name ORDER BY date_field DESC");
$current_date = "";
while ($row = $result->fetch_array()) {
if ($current_date != $row["date_field"]) {
echo "<h3>{$row['date_field']}</h3>";
$current_date = $row["date_field"];
}
// Print your entry from $row here.
}
you would probably want to get that in your SQL statement: (assuming it is datetime type)
SELECT * FROM table
WHERE date BETWEEN '2009-9-8 00:00:00' AND '2008-9-8
23:59:59'
Then just do your normal loop through your results
Also have a look at the GROUP BY clause of the SELECT statement.

How can I ignore time for NOW()?

I have a mysql database of entries
with dates. So what I want is to show
all the dates in my database and then
under each date, I want to show all
the entries in the database entered on
the specefic date. I am thinking of
two loops but I don't know how to
write the condition to display all the
dates in my database before I loop out
the entries under that date.
<?php
$sql = 'select start_date, name from events order by start_date';
$res = mysql_query($sql) or die(mysql_error());
$prev_date = null;
while ($row = mysql_fetch_assoc($res)) { if ($row['start_date'] != $prev_date) {
echo "<h1>{$row['start_date']}</h1>"\n;
$prev_date = $row['start_Date']; }
echo "<p>{$row['name']}</p>"; }
?>
In a previous question (Looping out mysql data), I resulted in using this code. It pulls the date and time from MYSQL, and I used NOW() to store both date and time. How can I make it ignore the time so I can achieve what I want?
as David Andres mentions in the comment, DATE() extracts the date part of a date or datetime expression. so you can do the following:
<?php
$sql = 'SELECT DATE(start_date) AS start_date_date, name FROM events ORDER BY start_date';
$res = mysql_query($sql) or die(mysql_error());
$prev_date = null;
while ($row = mysql_fetch_assoc($res)) {
if ($row['start_date_date'] != $prev_date) {
echo "<h1>$row[start_date_date]</h1>\n";
$prev_date = $row['start_date_date'];
}
echo "<p>$row[name]</p>";
}
Use CURDATE() instead of NOW().
Try it with a condition like this:
SELECT * FROM `events` WHERE DATE(`start_date`) = '2009-09-09';
This'll get you all events from the database for Sep 9th 2009. I think that's what you're asking for, is it?
Untested code that I will probably need someone to correct, but here goes:
SQL to retrieve all the dates that exist in the table:
$sql_get_dates = 'select start_date from events order by start_date distinct';
And, assuming start_date is a DATETIME type, the SQL to get all events on a given date:
$sql_get_events = 'select * from events where date(start_date) = "2009-08-09"';
Instead of just selecting the date, you could use some of the MySQL time functions to truncate the date.
$sql = "select date_format(start_date, '%Y-%m-%d') as fstart_date, name from events order by start_date";
Of course, you'll have to change start_date to fstart_date within the PHP code.
Check out the Mysql reference page for DATE_FORMAT().

Categories