MySQL/PHP update query with dates not updating - php

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.

Related

Posting a form with mysqli

I've created a web page working with php and mysqli in which I can send and edit MySQL entries without errors. The entries have title and date. The problem, appears when I try to change a date that is NULL.
Create an entry with date: Works
Create an entry without date: Works
Edit an entry with a date: Works
Edit an entry with a date to NULL: Works
Edit an entry with date NULL to an existing date: (doesn't work)
I've tried and tested things and I can assume that the problem is that the "day", "month" and "year" inputs are in blank/empty when the form is generated by PHP.
Also can't understand why the form to create an entry, which is exactly the same but with all the inputs in blank at the beginning, works in every case.
This is how I generate my form:
$mysqli->set_charset('Latin1');
$id=$_POST["id"];
$res = $mysqli->query("SELECT * FROM `list` WHERE `id`=$id");
while($row = $res->fetch_assoc()) {
if ($row["fecha"]==NULL) {$day="";$month="";$year="";}else{list($year, $month, $day) = explode("-", $row["date"]);};
echo "
<div class='home'>
<form accept-charset='Latin1' method='post' action='http://mypage.com/?opt=list&f=view'>
<input type='text' value='".$row['title']."' name='title' id='title' required><br>
<input type='number' value=".$day." name='day' id='day' min='1' max='31' placeholder='day'>
<input type='number' value=".$month." name='month' id='month' min='1' max='12' placeholder='month'>
<input type='number' value=".$year." name='year' id='year' placeholder='year'>
<input style='display:none;' type='number' value=".$id." name='id' id='id' placeholder='id'>
<input type='button' id='datepicker'><br>
<input type='submit' name='edit' value='Update'>
</form>
</div>";
};
And this is what happens when I submit:
$edit=$_POST["edit"];
if ($edit) {
$id=$_POST["id"];
$title=$_POST["title"];
if (empty($_POST["year"])&&empty($_POST["month"])&&empty($_POST["day"])){
$res = $mysqli->query("UPDATE `list` SET `title`=('$title'),`date`=(NULL) WHERE `id` = $id;");
}else{
$date=$_POST["year"]."-".$_POST["month"]."-".$_POST["day"];
$res = $mysqli->query("UPDATE `list` SET `title`=('$title'),`date`=('$date') WHERE `id` = $id;");
};
print ("Entry updated to ".$date); //When it doesn't works nothing appears in $date
};
I don't have any kind of idea of why it doesn't work JUST when the "day", "month" and "year" inputs are empty at the beginning.
PS. This is a solution (when date is NULL give values and then clear them when the form is generated), but I still don't know what is the problem with the inputs:
...
if ($row["fecha"]==NULL) {$day="0";$month="0";$year="0";}else{list($year, $month, $day) = explode("-", $row["date"]);};
echo "...";
if ($row["fecha"]==NULL){echo "<script>document.getElementById('day').value='';document.getElementById('month').value='';document.getElementById('year').value='';</script>";
...
Thanks to any help.
When you submit form, empty values from inputs are not submitted as null. They are submitted as empty string "" or zero in case of input which type is number.
Best way to avoid this is to use empty() function:
if (empty($_POST["year"]) && empty($_POST["month"]) && empty($_POST["day"])) {
// code ...
}
This function returns true when the variable is null, zero, false or empty.
Updated answer:
If you can't edit null date column to some date, make sure that:
That the column type of DATE
That your variables that contain year, month and day are formatted with precending zeros
Wrong examples: day = 5, month = 9
Good examples: day = '05', month = '09'
When you concate them as integers you get '2016-9-5' which is invalid date format.
So you should format them as strings with precending zeros like this '2016-09-05'.
Change this line of code:
$date=$_POST["year"]."-".$_POST["month"]."-".$_POST["day"];
To:
$date=sprintf("%04d-%02d-%02d", $_POST["year"], $_POST["month"], $_POST["day"]);
(Posted on behalf of the OP).
The problem was just syntax errors:
value= ' ".$day." '

Select date() HTML5 and match with SQL date

I am sooo stuck on this, cannot figure it out. I am trying to have the user select the date using the date selector in HTML5 and then query the sql database to find the date and output the results in a table below. I have been working on this for literally hours, cannot get past it, please help.
HTML
Date for retrieve: <input type="date" name="pickupDate" value="<?php echo $pickupDate;?>">
<span class="error">
</p>
<p>
Show date item for retrieve:
<input type="radio" name="input" value="requestDate1">Request Date
<input type="radio" name="input" value="pickupDate1">Pickup Date
</p>
<p><input type="submit" value="Show"></p>
$requestDate = mysqli_real_escape_string($db, isset($_POST["pickupDate"]));
PHP
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST["input"] == "requestDate1") {
$query = "SELECT requestDate FROM request WHERE requestDate = '$requestDate'";
echo "working";
I think your problem is with this selection query:
$query = "SELECT requestDate FROM request WHERE requestDate = '$requestDate'";
Please change it in this way:
$query = "SELECT requestDate FROM request WHERE requestDate = '" . $requestDate . "';";
Or if it's not working then check the date format both on frontend and backend, and if it's needed change the date format on backend to match it with frontend.
This is simple:
SQL uses the YMD HIS format to store date in to it's field, and HTML5 uses DDMMYYYY so if you want to use this date format, your required to change the format, I suggest you go through this answer in stackoverflow for more details...
HTML 5 Date format

else statement not triggering else

I am trying to create a script where if the date is later than today then it will display an item from the table in MySQL.
$query = $dbc->query("SELECT event_id, name, location, image, DATE_FORMAT(Date, '%d-%b-%Y') AS Date, Date as FormatDate
FROM events
ORDER BY FormatDate ASC
");
$results = $query->setFetchMode(PDO::FETCH_ASSOC);
while($row = $query->fetch()){
$name = $row['name'];
$image = $row['image'];
$location = $row['location'];
$Date = $row['Date'];
$Date = strtotime($Date);
$Date = date('d-M-Y', $Date);
$Data = explode("-", $Date);
if (strtotime($Date) >= time()){
$page->body("
<div class=\"event\">test
<img src=\"$image\" alt=\"$name\" class=\"event_image\"/>
<p class=\"event_title\">$name</p>
<p class=\"event_location\">$location</p>
<p class=\"event_time\">$Data[0] $Data[1] $Data[2]</p>
</div>
");
}else{
$page->body ("
<!-- alrge grey text 100% span -->
<div class=\"event\">
<p>There are currently no events happening.</p>
</div>
");
}
}
}
When I add an event to the table with a later date than today it adds successfully and the script runs and I can see the event printed out on the page because the date if greater than time().
But if I clear the MySql table of all events then it doesn't bring back the else statement "There are currently no events happening".
I am stumped as to why the else statement doesn't bring back the failed notification if there is nothing in the table that is later than today.
Any help much appreciated.
But if I clear the MySql table of all events then it doesn't bring back the else statement "There are currently no events happening".
The while statement will only execute if there are rows to process. Since you've cleared the table, it will never enter the while loop, and the else branch will never be encountered.
Because there are no rows to fetch and your code is not going inside while loop when your table is empty.
HTH!

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.

query between range of dates not showing results

I have a mysql database with a field called DATE, storing data as a date. I am trying to get the php date to select records for the next 31 days from the current date.
This is what I have...
$start_THISMONTH = "-1";
if (isset($to_date)) {
$start_THISMONTH = $to_date;
}
$finish_THISMONTH = "-1";
if (isset($from_date)) {
$finish_THISMONTH = $from_date;
}
mysql_select_db($database_WHTSON, $WHTSON);
$query_THISMONTH = sprintf("SELECT * FROM CALENDAR WHERE DATE BETWEEN %s AND %s AND APPROVED = 1 ORDER BY DATE ASC", GetSQLValueString($start_THISMONTH, "date"),GetSQLValueString($finish_THISMONTH, "date"));
$THISMONTH = mysql_query($query_THISMONTH, $WHTSON) or die(mysql_error());
$row_THISMONTH = mysql_fetch_assoc($THISMONTH);
$totalRows_THISMONTH = mysql_num_rows($THISMONTH);
-
The code to set up the two variables is
$from_date = date("Y-m-j");
$to_date = date('Y-m-j', strtotime("+31 days"));
And my php code in the body is
<h4><strong><font color="#FF0000"><?php echo $row_THISMONTH['EVENT_NAME']; ?></font></strong></h4>
<?php $date = date_format($row_THISMONTH['DATE'], 'jS F'); ?>
<h5><em><?php echo $date; ?>, <?php echo $row_THISMONTH['TIMES']; ?><br />
<?php echo $row_THISMONTH['LOCATION_ADDRESS']; ?>, <?php echo $row_THISMONTH['LOCATION_TOWN']; ?> <?php echo $row_THISMONTH['LOCATION']; ?></em><br />
</h5>
<p><?php echo $row_THISMONTH['EVENT_DETAILS']; ?><br />
</p>
No results are showing up. This is a new build database, and only one record is in there, with a date of Valentines Day. If I change the code to a simple "find all records" query it shows up great (though the date_format doesn't display a date.
This is my nemesis, please help me understand what I've done wrong?
If you have a date field column in mysql(YYYY-MM-DD) then try date('Y-m-d') instead of date('Y-m-j')
I have been staring at this for so long, but I think I have found one answer. I tried to be logical and use $to_date and $from_date, and then put them in the wrong order in the query. So although I haven;t actually solved the issue, I thinnk the issue is my untidyness on this occasion. I learnt a lot from the discussion too, thank you very much - time for a cleen sheet and a slower pace :)

Categories