PHP correct date format in MySQL query - php

I've posted an HTML form with input type date.
<input id="booking-date" name="booking-date" type="date" value="<?php echo date('Y-m-d'); ?>" required>
and receive the posted form values in PHP
$post_id = $_POST['post_id'];
$user_id = $_POST['user_id'];
$booking_date = $_POST['booking_date'];
$start_time = $_POST['start_time'];
$end_time = $_POST['end_time'];
$query = sprintf("SELECT * from %s WHERE `post_id`=%d AND `booking_date`=%s", $table, $post_id, $booking_date);
echo $query;
query doesn't return any result. When echo query it returns the following string with brackets at the end.
SELECT * from wp_appi_bookings WHERE `post_id`=367 AND `booking_date`=2023-02-13[]
How to resolve this issue with PHP?

Related

Search in between two different dates [duplicate]

This question already has answers here:
How do I query between two dates using MySQL?
(12 answers)
Closed 5 years ago.
I am trying out a search function. But instead of searching from a specific date, I am trying to search from a range of date so that it only displays data I want.
<form action ="searchreceipt.php" method ="post">
<input name="start" type="date" size="30" required />
<input name="end" type="date" size="30" required />
<input type="submit" value="Search"/>
</form>
<?php
$output = '';
if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);
$mysqli = new mysqli(spf, dbuser, dbpw, db);
$query = $mysqli->query("SELECT * FROM submission WHERE date BETWEEN 'start' AND 'end'") or die ("Could not search");
while ($row = $query->fetch_array(MYSQLI_ASSOC)) {
$officer_id = $row ['officer_id'];
$sbranch_no = $row ['sbranch_no'];
$carno = $row ['carno'];
$cost = $row ['cost'];
$area = $row ['area'];
$receipt = $row ['receipt'];
echo "<table border='1' style='width:50%'>";
echo "<td>";
echo "<b>Receipt ID: <a href ='transactiondetail.php?receipt=$receipt'>$receipt</b></a>";
echo "<br><br>";
echo "Used By: $officer_id";
echo "<br><br>";
echo "Officer Branch No: $sbranch_no";
echo "<br><br>";
echo "Cost: $cost";
echo "<br><br>";
echo "Area travelled: $area";
echo "<br><br>";
echo "</td>";
}
echo "</table>";
}
?>
You need to execute query like this
$startDate="2017-07-23";
$endDate="2018-01-01";
$query = $mysqli->query("SELECT * FROM submission
WHERE date BETWEEN '".$startDate."' AND '".$endDate."'")
;
Your query must be (ie.select * from table between lowerdate and upperdate):
Here lowerdate is 2017-12-26 10:37:45 and upper date is 2017-12-27 09:38:37
SELECT * FROM `table_name` WHERE (field_name BETWEEN '2017-12-26 10:37:45' AND '2017-12-27 09:38:37')
This will must work.
You needed to get parameter from header by using $_POST.
Try this below.
For more, you can refer here
$start = $_POST['start'];
$end = $_POST['end'];
$query = $mysqli->query("SELECT * FROM submission WHERE date BETWEEN '$start' AND '$end'") or die ("Could not search");

how to assign value of data box from database in php

Good morning to Everyone,
I have a Question regarding assigning the value date box from a database entry. I'm retrieving value from database DATE entry, assign it to a variable and that pass that variable to date box. bit i doesn't work.
first I retread the value from the database:
<?php
$conn = oci_connect('login', 'password', 'localhost/XE');
$myStr = "SELECT input_date FROM REc_INFO where idcode = 'RS0021'";
$stdi = oci_parse($conn, $myStr);
oci_execute($stdi);
$row = oci_fetch_array($stdi, OCI_BOTH);
$tempDate = $row[0];
$newDate = date("m/d/Y", strtotime($tempDate));
echo $newDate;
?>
I try to output $newDate to make sure its not empty and it returns the value of 03/27/2013. But when I try to pass $NewDate to the date box it doesn't work
<input type="date" name="sdate" id="sdate" value="<?php echo $newDate; ?>" required>
I wonder what am I doing wrong. Would be gratefull if someone can point it out to me.
Thanks in Advance.

Update query PHP MySQL [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
PHP UPDATE prepared statement
(3 answers)
Closed 11 months ago.
Can anybody help me understand why this update query isn't updating the fields in my database? I have this in my php page to retrieve the current values from the database:
<?php
$query = mysql_query ("SELECT * FROM blogEntry WHERE username = 'bobjones' ORDER BY id DESC");
while ($row = mysql_fetch_array ($query))
{
$id = $row['id'];
$username = $row['username'];
$title = $row['title'];
$date = $row['date'];
$category = $row['category'];
$content = $row['content'];
?>
Here i my HTML Form:
<form method="post" action="editblogscript.php">
ID: <input type="text" name="id" value="<?php echo $id; ?>" /><br />
Username: <input type="text" name="username" value="<?php echo $_SESSION['username']; ?>" /><br />
Title: <input type="text" name="udtitle" value="<?php echo $title; ?>"/><br />
Date: <input type="text" name="date" value="<?php echo $date; ?>"/><br />
Message: <textarea name = "udcontent" cols="45" rows="5"><?php echo $content; ?></textarea><br />
<input type= "submit" name = "edit" value="Edit!">
</form>
and here is my 'editblogscript':
<?php
mysql_connect ("localhost", "root", "");
mysql_select_db("blogass");
if (isset($_POST['edit'])) {
$id = $_POST['id'];
$udtitle = $_POST['udtitle'];
$udcontent = $_POST['udcontent'];
mysql_query("UPDATE blogEntry SET content = $udcontent, title = $udtitle WHERE id = $id");
}
header( 'Location: index.php' ) ;
?>
I don't understand why it doesn't work.
You have to have single quotes around any VARCHAR content in your queries. So your update query should be:
mysql_query("UPDATE blogEntry SET content = '$udcontent', title = '$udtitle' WHERE id = $id");
Also, it is bad form to update your database directly with the content from a POST. You should sanitize your incoming data with the mysql_real_escape_string function.
Need to add quote for that need to use dot operator:
mysql_query("UPDATE blogEntry SET content = '".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."'");
Without knowing what the actual error you are getting is I would guess it is missing quotes. try the following:
mysql_query("UPDATE blogEntry SET content = '$udcontent', title = '$udtitle' WHERE id = '$id'")
Here i updated two variables and present date and time
$id = "1";
$title = "phpmyadmin";
$sql= mysql_query("UPDATE table_name SET id ='".$id."', title = '".$title."',now() WHERE id = '".$id."' ");
now() function update current date and time.
note: For update query we have define the particular id otherwise it update whole table defaulty
First, you should define "doesn't work".
Second, I assume that your table field 'content' is varchar/text, so you need to enclose it in quotes. content = '{$content}'
And last but not least: use echo mysql_error() directly after a query to debug.
Try like this in sql query, It will work fine.
$sql="UPDATE create_test set url= '$_POST[url]' WHERE test_name='$test_name';";
If you have to update multiple columns,
Use like this,
$sql="UPDATE create_test set `url`= '$_POST[url]',`platform`='$_POST[platform]' WHERE test_name='$test_name';";
you must write single quotes then double quotes then dot before name of field and after like that
mysql_query("UPDATE blogEntry SET content ='".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."' ");

Making SQL entries appear only after current date - for a 'local events' page

I've been making an events page for a community website I'm creating. It allows them to create new SQL entries for new events.
What I want is to only display dates ahead of the current date
Currently I have:
SELECT * FROM eventsDB ORDER BY eventdate ASC LIMIT 30";
But I suppose I have to add something like:
WHERE eventdate > NOW()
For the record the above doesnt work ↑
note: ($eventdate = date of event)
CRONTAB:
<?php
class simpleCMS {
var $host;
var $username;
var $password;
var $table;
public function display_public() {
$q = "SELECT *
FROM eventsDB
WHERE eventdate > UNIX_TIMESTAMP()
ORDER BY eventdate ASC
LIMIT 30";
$r = mysql_query($q);
if ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_assoc($r) ) {
$title = stripslashes($a['title']);
$author = stripslashes($a['author']);
$bodytext = stripslashes($a['bodytext']);
$eventdate = stripslashes($a['eventdate']);
$created = stripslashes($a['created']);
$entry_display .= <<<ENTRY_DISPLAY
<div class="post">
<table class="eventstable" cellspacing="0" cellpadding="0">
<tr>
<td><img src="media/icons/icon_calendar.gif"/> <b>$title </b></td>
<td class="right">$eventdate </td>
</tr>
<tr>
<td colspan="2" class="small">$bodytext <i>by $author</i></td>
</tr>
</table>
</div>
ENTRY_DISPLAY;
}
} else {
$entry_display = <<<ENTRY_DISPLAY
<h2> Your brand new Events Page! </h2>
<p>
No entries have been made yet.
Follow my instructions to make a new event!
</p>
ENTRY_DISPLAY;
}
$entry_display .= <<<ADMIN_OPTION
<p class="admin_link">
</p>
ADMIN_OPTION;
return $entry_display;
}
public function display_admin() {
return <<<ADMIN_FORM
<form action="{$_SERVER['PHP_SELF']}" method="post">
<label for="title">Title:</label><br />
<input name="title" id="title" type="text" maxlength="150" />
<div class="clear"></div>
<label for="bodytext">Body Text:</label><br />
<textarea name="bodytext" id="bodytext"></textarea>
<div class="clear"></div>
<label for="author">Author:</label><br />
<input name="author" id="author" type="text" maxlength="100" />
<div class="clear"></div>
<label for="eventdate">Date (DD/MM/YY):</label><br />
<input name="eventdate" id="eventdate" type="text" maxlength="100" />
<div class="clear"></div>
<input type="submit" value="Create This Event!" />
</form>
<br />
Back to Events
ADMIN_FORM;
}
public function write($p) {
if ( $_POST['title'] )
$title = mysql_real_escape_string($_POST['title']);
if ( $_POST['bodytext'])
$bodytext = mysql_real_escape_string($_POST['bodytext']);
if ( $_POST['author'])
$author = mysql_real_escape_string($_POST['author']);
if ( $_POST['eventdate'])
$eventdate = mysql_real_escape_string($_POST['eventdate']);
if ( $title && $bodytext && $author ) {
$created = time();
$sql = "INSERT INTO eventsDB VALUES('$title','$bodytext','$created','$author','$eventdate')";
return mysql_query($sql);
} else {
return false;
}
}
public function connect() {
mysql_connect($this->host,$this->username,$this->password) or die("Could not connect. " . mysql_error());
mysql_select_db($this->table) or die("Could not select database. " . mysql_error());
return $this->buildDB();
}
private function buildDB() {
$sql = <<<MySQL_QUERY
CREATE TABLE IF NOT EXISTS eventsDB (
title VARCHAR(150),
bodytext TEXT,
created VARCHAR(100),
author VARCHAR(100),
eventdate VARCHAR(100),
)
MySQL_QUERY;
return mysql_query($sql);
}
}
?>
Based on our little discussion above, it seems like the easiest thing to do is make your eventdate field an INT data type. That way, when you take the user input as a string ("15/03/2011" for example), you can run that input through the PHP function strtotime() and get a UNIX timestamp from that.
<?php
$eventts = strtotime($_POST["eventdate"]);
$q = "UPDATE eventsDB SET eventdate = ".$eventts." WHERE keyfield = whatever";
$r = mysql_query($q);
?>
Note that strtotime() returns an INT (or boolean FALSE) so we're not setting you up for a SQL injection attack above. To query the database, you could then do this:
<?php
$q = "SELECT *
FROM eventsDB
WHERE eventdate > UNIX_TIMESTAMP()
ORDER BY eventdate ASC
LIMIT 30";
$r = mysql_query($q);
?>
To answer your question in the comments to this answer:
if ( $_POST['eventdate'])
$eventdate = mysql_real_escape_string($_POST['eventdate']);
Would be replaced with
if ( $_POST['eventdate'])
$eventdate = strtotime($_POST['eventdate']);
Note that for a production system, I really wouldn't recommend putting the admin code in the same page as the display code, and you should use the isset() function to check whether a $_POST array variable has been set (lest you cause all sorts of warnings or notices in your web server logs).
To display the date, you'd use the PHP date() function, specifically:
$entry_display = date("d/m/Y", $eventdate);
Where $eventdate is the UNIX timestamp you retrieved from the database.
The database is used or storing data.
PHP (or whatever you chose to use) is used for interacting with the user.
If you want to store a date, you should use a date datatype.
How you want to display the date, is up to your PHP code.
Probably you want to show the date in different formats depending on the visitor, or possible in ISO format so all of the world can read it: YYYY-MM-DD
So, your query is pretty much correct:
SELECT *
FROM eventsDB
WHERE eventdate > NOW()
ORDER BY eventdate ASC
LIMIT 30
Note that using 'SELECT *' is not recommended for production code. Only select the columns you need - it can mean better use of indices and less data transferred between your database and application server.
You can store eventdate field as UNIX timestamp and then compare it easily in your queries.
SELECT ... WHERE `eventdate` > NOW() ...
and you can format it with php date function :
date('DD/MM/YY', $eventdate);
here is the manual : PHP Date Function

MySQL/PHP update query with dates not updating

Bit of a strange problem here...
I've got an update query that isn't working, and I can't for the life of me work out why!
My table has two three fields - 'id' (int, auto increment), 'date' (date), and 'amountraised' (decimal). Part of the app I'm developing calculates the fundraising total each week made by a charity bookstall. The 'date' field uses a date column type as elsewhere on the site I'm using the dates in calculations.
Elsewhere within the system I've got other update queries that are working just fine, but I suspect the problem with this one is that as well as updating the record I'm also trying to manipulate the date format as well (so that I can enter dates in the British dd-mm-yyyy format and then use the PHP to convert back into the MySQL-friendly yyyy-mm-dd format.
This is the strange bit. According to the confirmation page on the site, the query has run okay, and the update's been made, but when I check the database, nothing's changed. So I could check what the output of the query is I've tried echoing the result to the web page to see what I'm getting. The expected values show up there on the page, but again, when I check the database, nothing's been updated.
This is my update form with the date conversion function:
function dateconvert($date,$func) {
if ($func == 1){ //insert conversion
list($day, $month, $year) = split('[/.-]', $date);
$date = "$year-$month-$day";
return $date;
}
if ($func == 2){ //output conversion
list($year, $month, $day) = split('[-.]', $date);
$date = "$day/$month/$year";
return $date;
}
} // end function
require_once('/home/thebooks/admins/connect.php');
$id = $_GET['id'];
$dateinput = $_GET['dateinput'];
$query = "SELECT * FROM fundraisingtotal WHERE id='$id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
extract($row);
$date = $row['date']; //your mysql date
$realdate = dateconvert($date,2); // convert date to British date
$amountraised = stripslashes($amountraised); //amount raised
mysql_close();?>
<div id="title">Update Fundraising Total</div>
<form id="updatetotals" action="updated.php" method="post">
<div class="row"><label for="dateinput" class="col1">Date </label><span class="col2"><input id="dateinput" name="dateinput" type="text" size="25" value="<?php echo $realdate ?>" maxlength="10" /></span></div>
<div class="row"><label for="amountraised" class="col1">Fundraising Total </label><span class="col2"><input id="amountraised" name="amountraised" type="text" size="25" value="<?php echo $amountraised ?>" maxlength="7" /></span></div>
<div class="submit"><input type="submit" name="submitted" value="Update" /><input type="reset" name="reset" value="Clear the form" /></div>
<input type="hidden" name="id" value="<?php echo $id ?>" />
</form>
...and this is the form processing/query page:
require_once('/home/thebooks/admins/connect.php');
$dateinput = $_POST['dateinput'];
// Date conversion from: http://www.phpbuilder.com/annotate/message.php3?id=1031006
// using type 1
$convdate = $_POST['dateinput']; // get the data from the form
$convdate = dateconvert($convdate, 1); // Would convert to e.g. 2005-12-19 which is the format stored by mysql
function dateconvert($convdate,$func) {
if ($func == 1){ //insert conversion
list($day, $month, $year) = split('[/.-]', $convdate);
$date = "$year-$month-$day";
return $date;
}
if ($func == 2){ //output conversion
list($year, $month, $day) = split('[-.]', $convdate);
$date = "$day/$month/$year";
return $date;
}
}
$date = "$convdate";
$amountraised = $_POST['amountraised'];
$update = "UPDATE fundraisingtotal SET date = '$date', amountraised = '$amountraised' WHERE id='$id' ";
$result = mysql_query($update);
$realdate = dateconvert($date,2); // convert date to British date
if ($result) {
echo "<p class=\"dbpara\">Thank you. Your update to the record was successful.</p>";
echo "<p class=\"dbpara\">The record has been amended to a date of <b>$realdate</b> and amount of <b>$amountraised</b>.</p>";
}
else {
echo "<p>Nothing has been changed.</p>";
}
mysql_close();
The weird thing is that the confirmation text "The record has been amended to...etc." displays exactly as expected, but when I check the database, the record hasn't been updated at all.
I'm sure it must be something I'm missing with messing with the date formats or I've got something in the wrong order, but I've tried so many different variations on this now I can't see the wood for the trees. Anyone any ideas what I'm doing wrong here?
I see some red-flags here. You are getting the date from a form and inputing it into MySQL without any form of validation - that could lead to SQL-injections.
Start by changing dateconvert function to something more secure. This function will always return a correct formated date, even if the user tries to abuse the system.
Edit 1: Forgot to put a : after case 'en_en' but fixed it now. Thanks neonblue.
Edit 2: Forgot to feed the date() function with the timestamp. Fixed!
Edit 3: A preg_replace to convert frontslashes to dashes
// this function always returns a valid date
function dateconvert($date = NULL, $date_type = 'sql') {
$date = preg_replace("/", "-", $date);
$timestamp = strtotime($date);
switch($date_type) {
default: case 'sql' : return date('Y-m-d', $timestamp); break; // prints YYYY-MM-DD
case 'en_EN' : return date('d-m-Y', $timestamp); break; // prints DD-MM-YYYY
}
}
You can always have a look into Zend_Date that will let you work with dates on your own format.
Change
$result = mysql_query($update);
to
$result = mysql_query($update) or die(mysql_error());
And you should see what the problem is when the query fails.
Three things I would look for:
Is the code attaching to the same database you are looking at? (I spent a few hours on this one ;)
Is another update statement (or this one) running immediately afterwards that would change the values back? Here you need some logging to figure it out.
If you echo the sql, what happens when you run it directly yourself?
If you see the table is not changing any value but the query does not show you any error, then WHERE id = '$id' is not hitting the register you intended to.
Don't forget to sanitize your queries as others are telling you.

Categories