How to use MONTHNAME in a MySQL query to match months - php

I'm building a query so I can get a list of new users by month:
public function getNewUsers($month) {
$month = date('F', strtotime($month));
$sql = "SELECT * FROM `{$this->table}` WHERE MONTHNAME(`account_creation_date`) = {$month} ORDER BY `id` DESC";
$stmt = $this->pdo->prepare($sql);
$stmt->execute([$month]);
if ($stmt->rowCount() == 0) return null;
$users = $stmt->fetchAll(PDO::FETCH_NAMED);
foreach ($users as &$user) {
$user = $this->applyRelations($user);
}
return $users;
}
An example of "account_creation_date" value is "08/08/2019 4:55 pm"
Im trying to pass in a month name like "August" and have the query convert the account_creation_date values to their month names.
Although I'm getting no errors, nothing is returning when the query is executed.
How can I accomplish this? Is MONTHNAME what I want?
Thanks!

Related

Date filter function with SQL doesn't work

I have a website where I load various activities who all have a specific date. I want to filter on those dates.
I do that with this query:
function selectAllActivities($date = false){
$sql = "SELECT * FROM `activities`
INNER JOIN `locations` on `activities`.`location_id` = `locations`.`id`";
if (!empty($date)){
$sql .= " WHERE `activities`.`start` >= :date AND `activities`.`start` < :next_day";
}
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(':date', strtotime($date));
$stmt->bindValue(':next_day', strtotime($date.'+1 day'));
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
If there is no date given, the page will load all the activities, but if someone wants to select a specific date to see which activities there are on that date, I use this code:
public function index() {
$activityDAO = new ActivityDAO();
if (!empty($_GET['date'])) {
$activities = $activityDAO->selectAllActivities($_GET['date']);
} else {
$activities = $activityDAO->selectAllActivities();
}
$this->set('activities',$activities);
}
The page loading of all the activities is working fine, but if I select a specific date, the array with activities stays empty and no activities will load.
Since the column is Datetime , in your sql , you are injecting timestamp value , so that cause that yor result is always empty .
Instead , you can convert Date given to datetime with the same format 'Y-m-d-h-m' using gmdate:
function selectAllActivities($date = false){
$sql = "SELECT * FROM `activities`
INNER JOIN `locations` on `activities`.`location_id` = `locations`.`id`";
if (!empty($date)){
$sql .= " WHERE `activities`.`start` >= :date AND `activities`.`start` < :next_day";
}
$dateTime = gmdate("Y-m-d-h-m", strtotime($date));
$dateTimeTomorrow=gmdate("Y-m-d-h-m", strtotime($date.'+1 day'));
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(':date', $dateTime);
$stmt->bindValue(':next_day', $dateTimeTomorrow);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

Query returing only last value in codeigniter

I am new to CI/PHP/development. Im stuck on this problem. It seems to be really basic but i just cant get it right!
I am able to returning only last value while sql excecution .
controller
$data['leadd']= $this->dashboard_model->countt($this->session->userdata('user_id'));
foreach ($data['leadd'] as $q) { $date = $q['followup_date'];
$data['lead']= $this->dashboard_model->lead_count($this->session->userdata('user_id'),$date); }
$data['count'] = count($data['lead']);
Model
public function countt($userid)
{
$sql = $this->db->query("SELECT followup_date FROM tg_partner_data WHERE assign_to = '$userid' AND active = 'Y'");
return $sql->result_array();
}
public function lead_count($userid,$date)
{
$sql1 = $this->db->query("SELECT * FROM tg_partner_data
WHERE assign_to = '$userid' AND followup_date = '$date'
AND active='Y'");
//echo $this->db->last_query();
return $sql1->result_array();
}
First you select all followup dates from one table by executing this: "SELECT followup_date FROM tg_partner_data WHERE assign_to = '$userid' AND active = 'Y'".
Then for each followup_date, you execute another query but you don't merge prevoius results just overwrites them in foreach loop.
Foreach loop should look like this:
$data['lead'] = array();
foreach ($data['leadd'] as $q) {
$date = $q['followup_date'];
$data['lead'][] = $this->dashboard_model->lead_count($this->session->userdata('user_id'),$date));
}
You can also rewrite SQL query:
SELECT COUNT(*) FROM tg_partner_data WHERE assign_to = '$userid' AND followup_date = '$date' AND active='Y'"
It will allow you to get number of rows directly from DB.

Wordpress get user by date returns empty list

I have a function that lists all the users that registered today but for some reason it returns an empty result
function get_user_by_date($start=null,$end=null){
global $wpdb;
if ($start == null && $end == null){
$end = date("Y-m-d");
}
echo $end;
$query = "SELECT * FROM wp_users WHERE user_registered >= %s";
$prep = $wpdb->prepare($query,$end);
echo $prep;
$results = $wpdb->get_results($prep);
return $results;
}
Query looks like this when I tried to echo prepared statement
SELECT * FROM wp_users WHERE user_registered >= '2015-02-27'
When I use this query in my PHPMyAdmin, it works fine. Can you please tell me what I am doing wrong?
Try to:
$query = "SELECT * FROM wp_users WHERE user_registered >= DATETIME(%s)";
and here:
$end = date('Y-m-d H:i:s');

how to pass the php variable in Mysql select Query

$valid is An array and $createdon and $days are get the Date value from array.
My select query is not work with these date value of PHP variable please solve its.
function checkexpiretime($valid)
{
$db = &JFactory::getDBO();
foreach($valid as $validity)
{
echo $createdon=$validity->CreatedOn;
echo $days=$validity->days;
}
echo $query="SELECT * FROM jos_generatekey WHERE CreatedOn BETWEEN DATE_ADD('".$createdon."',".INTERVAL $days DAY.")". "AND CURDATE()";
$db->setQuery($query);
$checkexpire = $db->loadObjectList();
print_r($checkexpire);
return $checkexpire;
}
Query should be like this:
$query= "SELECT * FROM jos_generatekey WHERE CreatedOn BETWEEN DATE_ADD('".$createdon."',INTERVAL ". $days ." DAY) AND CURDATE()";

How can I add array values to a MySQL query?

I'm using the following code to sort MySQL queries into time/date:
mysql_select_db("user_live_now", $con);
$result = mysql_query("SELECT * FROM users_newest_post ORDER BY users_date_post DESC");
while($row = mysql_fetch_array($result))
{
print($row['user']);
}
instead of having the PHP run through and show all the values in the table can I have it show the values from an array?
So, you want to find specific users in the SQL query to return? Build your query programmatically:
$users = array('User1','John','Pete Allport','etc');
$sql = "SELECT * FROM `users_newest_post` WHERE ";
$i = 1;
foreach($users as $user)
{
$sql .= "`username` = '$user'";
if($i != count($users))
{
$sql .= " OR ";
}
$i++;
}
$sql .= " ORDER BY `users_date_post` DESC";
$result = mysql_query($sql);
Which would get you a query like:
SELECT * FROM `users_newest_post`
WHERE `username` = 'User1'
OR `username` = 'John'
OR `username` = 'Pete Allport'
OR `username` = 'etc'
ORDER BY `users_date_post`
DESC
So, you want to find all posts for a certain date or between two dates, kinda hard to do it without knowing the table structure, but you'd do it with something like this:
//Here's how to find all posts for a single date for all users
$date = date('Y-m-d',$timestamp);
//You'd pull the timestamp/date in from a form on another page or where ever
//Like a calendar with links on the days which have posts and pass the day
//selected through $_GET like page.php?date=1302115769
//timestamps are in UNIX timestamp format, such as you'd get from time() or strtotime()
//Note that, without a timestamp parameter passed to date() it uses the current time() instead
$sql = "SELECT * FROM `posts` WHERE `users_date_post` = '$date'"
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results))
{
echo $row['post_name'] . $row['users_date_post']; //output something from the posts
}
//Here's how to find all posts for a range of dates
$startdate = date('Y-m-d',$starttimestamp);
$enddate = date('Y-m-d',$endtimestamp);
//Yet again, date ranges need to be pulled in from somewhere, like $_GET or a POSTed form.
//Can also just pull in a formatted date rather than a timestamp and use it straight up instead, rather than going through date()
$sql = "SELECT * FROM `posts` WHERE `users_date_post` BETWEEN '$startdate' AND '$enddate'";
//could also do:
//"SELECT * FROM `posts` WHERE `users_date_post` > '$startdate' AND `users_date_post` < '$endate'"
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results))
{
//output data
}
To find posts for a specific user you would modify the statement to be something like:
$userid = 5; //Pulled in from form or $_GET or whatever
"SELECT * FROM `posts` WHERE `users_date_post` > '$startdate' AND `users_date_post` < '$enddate' AND `userid` = $userid"
To dump the result into an array do the following:
mysql_select_db("user_live_now", $con);
$result = mysql_query("SELECT * FROM users_newest_post ORDER BY users_date_post DESC");
while($row=mysql_fetch_assoc($result))
{
$newarray[]=$row
}
What you probably want to do is this:
$users = array("Pete", "Jon", "Steffi");
$users = array_map("mysql_real_escape_string", $users);
$users = implode(",", $users);
..("SELECT * FROM users_newest_post WHERE FIND_IN_SET(user, '$users')");
The FIND_IN_SET function is a but inefficient for this purpose. But you could transition to an IN clause with a bit more typing if there's a real need.
$sql = 'SELECT * FROM `users_newest_post` WHERE username IN (' . implode(',', $users) . ')';

Categories