I have a form in my app. This form consists of 2 textfields type='date'. Now, when two dates are given, the dates are send to a PHP-script that translates the dates with strtotime.
The PHP-script makes a connection to a mySQL database that returns a result with requests. I would like to loop through all requests and check if the date of the request is BETWEEN the two dates that where sent by the form.
What happens now:
$sql = "SELECT * FROM Requests";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($result) {
foreach ($result as $row){
$return[]=array('employeeid'=>$row['employeeid']
'id'=>$row['id'],
'startdate'=>$row['startdate'],
'enddate'=>$row['enddate'],
'type'=>$row['type'],
'reason'=>$row['reason']);
}
header('Content-type: application/json');
echo '' . json_encode($return) .'';
return true;
} else {
return false;
}
The code above generates a perfect json-file with the requests. But as I mentioned I would like to check whether the startdate of the requests above is between the two dates that are send by the form.
Something like this:
if (($request_startdate >= $startdate) && ($request_startdate <= $enddate)) {
//generate array with the requests
} else {
//no requests between dates.
}
But how to loop through the requests and check the startdate?
Thanks in advance.
Jan
You are taking the hard way, it's easier to add a where statment to your select query:
I assume that your form have two fields named date1, date2
$sql = "SELECT * FROM Requests where startdate>:date1 and enddate<:date2";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':date1',$_POST['date1'],PDO::PARAM_STR);
$stmt->bindValue(':date2',$_POST['date2'],PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
Convert your string inputs to DateTime and format it to ISO date format (or at least make sure they are in a format that mySQL accepts)
$sdt = DateTime::createFromFormat('format of your input', $request_startdate);
$edt = DateTime::createFromFormat('format of your input', $request_enddate);
Modify your sql to query only the rows that you want to use:
SELECT * FROM Requests
WHERE startdate <= :sdt AND :edt >= :edt
Then bind your parameters (see php doc):
$stmt->bindParam(':sdt', $sdt->format('YYYY-mm-dd 00:00:00'), PDO::PARAM_STR);
$stmt->bindParam(':edt', $edt->format('YYYY-mm-dd 23:59:59'), PDO::PARAM_STR);
Related
I'm trying to make it so that when the checkbox is selected it puts today's date in the database, I tried using timestamp but it puts it in all the spaces in the column, I'm a beginner in php
The code I made was this:
<?php
if (isset($_POST['Abate'])){
$Abate="Sim";
$data=time();
$DiaAbate= date("Y/m/d", $data);
}
else{
$Abate="Nao";
$DiaAbate="";
}
?>
You have not included your table structure (CREATE TABLE statement) so I have assumed you have a DATE column for storing $DiaAbate. I have also assumed that the submitted date is in 22/11/2022 format. If you are using a different format for the POSTed date value, you will need to change the format string passed into DateTime::createFromFormat().
Your current code is vulnerable to SQL Injection as you are combining your static strings with user input without any validation. The simple example below uses a prepared statement for the insert query -
if (isset($_POST['Abate'])){
$Abate = 'Sim';
// create a date from the posted date string adn format it
// see https://www.php.net/manual/en/datetime.createfromformat.php
$DiaAbate = DateTime::createFromFormat('d/m/Y', $_POST['DiaAbate'])->format('Y-m-d');
} else {
$Abate = 'Nao';
$DiaAbate = null;
}
$query = 'INSERT INTO pc (Abate, DiaAbate) VALUES (?, ?)';
$query_run = mysqli_execute_query($con, $query, [$Abate, $DiaAbate]);
if ($query_run) {
$_SESSION['status'] = 'Inserted Succesfully';
header('Location: indexx.php');
} else {
$_SESSION['status'] = 'Not Inserted';
header('Location: indexx.php');
}
I want to send a reminder to my subscribers a month before their subscription ends, i have columns validity and reminder (type VARCHAR) in my MYSQL DB
date stored in those columns are saved using php date function
$validity = date('d/m/Y',strtotime("6 months"));
$reminder = date('d/m/Y',strtotime("5 months"));
now i want to send a mail when the current date is equals reminder date
I have a test entry with reminder value 22/06/2017 and $date variable echo the same value.
$date = date('d/m/Y');
$q = 'SELECT * FROM subscriptions WHERE reminder = "$date"';
$r = mysql_query($q);
if(!$r){
echo 'query err';
}
$a = mysql_num_rows($r);
echo 'No of rows returned '.$a;
*mailing script after this line*
this script outputs No of rows returned 0
Can someone give me some idea how i should approach this
First i suggest you your date format is change in database and type change datetime.
This format follow for you insert reminder date
$reminderdate = date('Y-m-d');
Then compare with currentdate when fetch data from database:
$date=date('Y-m-d');
if($r['reminder']==$date)
{
echo 'Mail sent here';
}
else
{
echo 'date not match';
}
Your script is at risk for SQL Injection Attacks, see this
The issue is here:
'SELECT * FROM subscriptions WHERE reminder = "$date"';
change it to:
"SELECT * FROM subscriptions WHERE reminder = '".$date."'";
to compare date, you have to wrap it into single quotes '
A few suggestions:
the reminder column may be redundant depending on your logic
in the future please use different approach to connect to the database, for example: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
the validity column should rather be DATETIME format
Now to your main question - it can be because of datetype mismatch so switch in database to DATETIME and in PHP use date('Y-m-d').
First Of all You should not store date in varachar.
Now to compare dates in varchar first you have to convert the string(varchar) into date.
for that you can use mysql's function:
str_to_date
You can get the example how to convert it and then compare it to get the result.
$q = "SELECT * FROM subscriptions WHERE reminder = '{$date}'";
I Know You have selected the answer already and ignored the comments, because you just want to get this done with and move on no matter how you did it. I will just make this answer a community WIKI.
Below are the things you need to note :
The API that you are using have depreciated for a long time ago rather use mysqli or even better PDO with prepared statements.
Also What I'm sure when the use subscrips on your website, you should have a column that stores the duration of the subscription and the actual expire date and a flag to identify expired subscriptions.
Mysql does provide its own date time functions, which you can use and use the date type on these columns.
Use API that is still active and maintained that is mysqli_* or pdo they both support prepared statements.
$host = '127.0.0.1';
$db = 'DBNAME';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
);
$dbh = new PDO($dsn, $user, $pass, $opt);
$stmt = $dbh->query("SELECT * FROM subscriptions WHERE subscriptionsExpireColumn = DATE_ADD(CURDATE(), INTERVAL 1 MONTH)");
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
} else {
$results = $stmt->fetchall();
if (count($results) > 0) {
foreach ($results as $row) {
//DO WHAT EVER YOU WANT TO DO WITH THE RESULTS
}
} else {
echo "no records found";
}
}
?>
I am currently doing a event scheduling module for my system. I want to count all the scheduled events for all months.. For example I have 10 events for this march, then 5 incoming events in April but I am encountering error "A Database Error Occurred"
CONTROLLER
$data['getAll'] = $this->CrudModel->count_all('events');
MODEL
public function count_all($table)
{
// $this->db->select('service');
// $this->db->from($table);
// $this->db->where('date LIKE','%'.$month.'%'); // 2017-03-04
// $num_results = $this->db->count_all_results();
// return $num_results->result();
$query = $this->db->query("SELECT date, service from $table");
foreach ($query->result() as $row)
{
# code...
$date = $row->date;
$service = $row->service;
$date_explode = explode('-', $date);
$year = $date_explode[0];
$month = $date_explode[1];
$day = $date_explode[2];
$service_explode = explode(',', $service);
echo "<pre>";
print_r($date_explode);
print_r($service_explode);
echo "</pre>";
$this->db->like('date',$month); // 2017-03-04
$num_results = $this->db->count_all_results();
}
// return $query->result();
}
Question: Is my query wrong? If yes what is it? Or any other suggestion how to count all the scheduled events?
NOTE: I only used one date.. The scheduled date(Eg. I scheduled the event in 2017-03-04), i dont have end date(cause I used the date input type in html)
you must specify table name
$this->db->count_all_results("table");
Active Record Documentation for count_all_results();
Looks to me like the query is missing a FROM clause and tablename. (Or an inline view query in place of an identifier.)
MySQL (or MariaDB) Server is reporting a syntax error, flagging the the WHERE keyword. MySQL is expecting the statement to have FROM clause, and is not finding it.
The error message reports that an invalid statement was issued, looks like this:
SELECT COUNT(*) AS `numrows` WHERE ...
What's missing is the FROM keyword and a table_name:
SELECT COUNT(*) AS `minimums` FROM some_row_source WHERE ...
^^^^^^^^^^^^^^^^^^^^
Maybe $table is being evaluated as an empty string?
For debugging this, I'd suggest first figuring out which line(s) of code is causing this SQL statement to be executed.
I have some data in my table which are [name][address][phone_number] and the date in this format 2015-10-14 14:37:38. I am using php PDO. How can I query out just today date from the table?
The following code is my code to query out result for the past 7 days which worked perfectly. However, whenever I replace it with 1 it doesn't work:
$query = $digital->query('SELECT * FROM sales WHERE `datetime` BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW() ORDER BY sale_id DESC');
What I want is to be able to query out all today data inserted into database.
You can use this, haven't tested.
<?php
$todaysDate = date('Y-m-d'); //if your date is stored in y-m-d format
try
{
$s = $conn->query("SELECT * from sales where datetime LIKE '%$todaysDate%'");
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$results = $s->fetch(PDO::FETCH_OBJ);
?>
Your query results is now in $results variable.
Extended version
<?php
try
{
$s = $conn->query("SELECT * from sales");
}
catch(PDOException $e)
{
echo $e->getMessage();
}
while($results = $s->fetch(PDO::FETCH_OBJ))
{
$date = explode(" ", $results->datetime);
if($date[0] == date('Y-m-d'))
{
//write code here to display data
}
}
?>
Make sure you replace all the columnNames and tablename.
Edit :-
Here's a sqlfiddle pertaining to my first solution.
http://sqlfiddle.com/#!9/7c2f1/3
I dont know whether it applies to PDO, as I'm not very acquainted to it, but I use to pass the date in a var, then ask for a match in my sql statement
// choose your own timezone here
date_default_timezone_set('America/Sao_Paulo');
// then define your variable as the current time:
$date = date("Y-m-d H:i:s");
then, i'd use the correct PDO syntax to compare the column with the var (a simple "where" statement should do it).
(using codeigniter syntax)
$this->db->where('date', $date);
Trying to figure out why my code isn't working. Basically I have an elseif statment like so:
mysql_connect("localhost","xxxx","xxxxx");
mysql_select_db("xxxxxx");
$sql = "SELECT COUNT(DATE) FROM calendar";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$checkdate = $row['DATE'];
$DATEFROM = $_POST['DATEFROM'];
$DAYCOUNT = $_POST['DAYCOUNT'];
$DAYS = $_POST['DAYS'];
if ( $DAYCOUNT < $DAYS ) {
header( 'Location: request_go_fail.php' );
}
else if ( $checkdate == $DATEFROM ) {
echo "FAIL!";
}
else {
It doesn't work, the first check (to see if the DAYCOUNT is less than DAYS works fine, but when comparing to entries in the DB it doesn't seem to do it. Seems to be some issue with finding the already existing data, as when I change $checkdate to an entry that's already in the database it works great.
Any help is most appreciated :)
SELECT COUNT(DATE) FROM calendar doesn't return a field called date, print_r the $row variable to confirm that. Best solution is to change the statement to something like SELECT COUNT(DATE) AS datecount FROM calendar and then do $checkdate = $row['datecount'];
But while rereading your code fragment, I'm not sure that you really want the count of DATE's in the calendar table, and what exactly the intention is, is hard to determine from the code fragment.
Also, DATE is a reserved word in SQL, not the optimal choice for a column name!
Did you try printing $checkdate? I suspect it's null if that is indeed the SQL you're using.
Should be $row['COUNT(DATE)'] I believe, or you can use mysql_fetch_array and $row[0] instead, or use an AS in your SQL or
$checkdate = mysql_result($result, 0);
And skip the fetch call all together.
COUNT(DATE) will return the number of non-null DATE fields in your DB btw, is that really what you want?
You don't have a DATE key in the $row variable because of the sql command. Use this instead, it's called Alias:
SELECT COUNT(DATE) AS DATE_COUNT FROM calendar
Now you have a key DATE_COUNT which will contains value.
$checkdate = $row['DATE_COUNT'];