I am creating a form that extracts user info, and the users can update their info if needs be. On the form there are two date fields, the second field is optional. So when the user clicks UPDATE and the second date field is blank, in MSSQL database it updates the date_two field with "01/01/1970". I am using PHP with MSSQL, so in the code I have:
if(isset($_POST['update']) {
$date_two = $_POST['date_two'];
if($date_two == "")
$date_two == NULL;
else
$date_two = date("Y-m-d", strtotime($date_two) );
UPDATE table SET date_two = CAST('$date_two' as DATE2);
}
The resulted entry is 01/01/1970, instead of NULL.
you should check if your input date value is a emprty string ('') and manage for null because if the value of your var is not null (also an empty string)
the update produce a date value
UPDATE table SET date_two = (case when '$date_two' = '' then NULL
else CAST('$date_two' as DATE2)
end);
anyway you should not use php var in your sql command you are at rusk for sqlinjection .. take a lool at you db driver fior prepared command and binding param ..
Related
I am in problem is that, i am using php ms access databse, when i am trying to update date in database its not updating, i want to update date field when user put date and when date is null column value should be null, my code following
if($cDate==NULL){
$cDate='Null';
}
else {
$cDate='02/03/2016';
}
if($buttonName=="Update"){
$sql_update="UPDATE 0D1_INDEX set C_date=$cDate where DN_='$mdn'";
and when date inserted it become time
Try This,
Set Default Value to NULL in Database
If I understand your question correctly you could use the isset() function to determine if the value of $cDate is null.
So you would have to do something like so:
if(!isset($cDate)){
$cDate = "Null";
} else{
$cDate='02/03/2016';
}
isset() determines if the value is not NULL so putting an ! in front of it means that if the value is NULL
This question already has answers here:
How to store NULL values in datetime fields in MySQL?
(9 answers)
Closed 7 years ago.
I have optional date and time form fields which are combined to form a DATETIME-friendly string, which is then sent to the MySQL database. The relevant MySQL column data type is DATETIME, with a default value of NULL. It saves correctly when the date and time fields are completed; however when these optional form fields are empty, the datetime is stored as 0000-00-00 00:00:00 instead of NULL. It needs to be stored as NULL and I have no idea why it isn't. Here's my code:
$Date_Query_Received1 = mysqli_real_escape_string($conn, $_POST['Date_Query_Received']);
$Date_Query_Received2 = implode("-", array_reverse(explode("/", $Date_Query_Received1)));
$Time_Query_Received1 = mysqli_real_escape_string($conn, $_POST['Time_Query_Received']);
$Time_Query_Received2 = $Time_Query_Received1.':00';
if (empty($_POST['Date_Query_Received']) || empty($_POST['Time_Query_Received'])) {
$Date_Query_Received = NULL;
$Time_Query_Received = NULL;
} else {
$Date_Query_Received = $Date_Query_Received2;
$Time_Query_Received = $Time_Query_Received2
}
$Date_Time_Query_Received = $Date_Query_Received.' '.$Time_Query_Received;
mysqli_query($conn, "INSERT INTO log (Date_Time_Query_Received) VALUES ('$Date_Time_Query_Received')";
The form dates are in DD/MM/YYYY format, hence implode(...array_reverse(...)) to convert to MySQL-friendly DATETIME YYYY-MM-DD format. The same applies with appending ':00' to the time value, as the form field jQuery timepicker is set up for hh:mm only - seconds are not required.
Perhaps it has something to do with the quotes around $Date_Time_Query_Received in the SQL statement; however the query fails without them.
So if you look at your query, you were trying to set the date column to the string ' ' which obviously isn't going to make MySQL happy. It's a very forgiving database though, and defaults to its fallback for a DATETIME column, which is 0000-00-00 00:00:00.
So, how do you pass a null value to the database from PHP? Try using prepared statements like so:
if (empty($_POST['Date_Query_Received']) || empty($_POST['Time_Query_Received'])) {
$Date_Time_Query_Received = NULL;
} else {
$Date_Query_Received2 = implode("-", array_reverse(explode("/", $_POST['Date_Query_Received'])));
$Time_Query_Received2 = "$_POST[Time_Query_Received]:00";
$Date_Time_Query_Received = "$Date_Query_Received2 $Time_Query_Received2";
}
$stmt = $conn->prepare("INSERT INTO log (Date_Time_Query_Received) VALUES (?)");
$stmt->bind_param("s", $Date_Time_Query_Received);
$stmt->execute();
In addition to making it easier to pass the null value, you're also protecting yourself from SQL injection attacks more effectively than with mysqli_real_escape_string().
Ok, this is driving me crazy!!
Got a MySQL table with an integer field default set to null.
Need to update it through a form submission. If form field is blank, set database field to NULL, ELSE set database field to form submission value.
So, in PHP I have: (staging code, still needs to be sanitized)
if($_POST['vendor-product'] != ''){
$ms2VendorID = $_POST['vendor-product'];
}else{
$ms2VendorID = '';
}
The problem is that instead of NULL it enters a zero. I've tried several different ways and nothing seems to be working.
Thanks for any help.
Why don't you assign NULL (as a string) to your variable in the else statement?
if($_POST['vendor-product'] != ''){
$ms2VendorID = $_POST['vendor-product'];
}else{
$ms2VendorID = "NULL";
}
Also, make sure that the field has not the NOT NULL constraint enabled.
I'm trying to filter out repeated values entering into a MySQL table, by comparing the input PHP variable with the timestamp of an entry already present in the table and only if they don't match, the input PHP variable is entered into the table.
$user1_date = mysql_real_escape_string($user1_date); // the date variable
$user1_temp1 = mysql_real_escape_string($user1_temp1);
$user1_temp2 = mysql_real_escape_string($user1_temp2);
$user1_temp3 = mysql_real_escape_string($user1_temp3);
$user1_date = date("Y-m-d H:i:s", strtotime($user1_date)); //Typecasting PHP variable into timestamp
$sql_check = "SELECT * FROM user_details WHERE temp_date ='$user1_date'";
$result_check = mysql_query($sql_check);
$num_rows_check = mysql_num_rows($result_check);
if ($num_rows_check == 0) // To check if there is no entry in the table with the same date and time as input PHP variable
{
$sql_insert = "INSERT INTO data_hour (user_id, temp1, temp_date, temp2, temp3)
VALUES (1,'$user1_temp1', '$user1_date', '$user1_temp2', '$user1_temp3')";
$result_insert = mysql_query($sql_insert);
}
temp_date is a column in the table of type timestamp. Even when the $user1_date is the same as the temp_date(timestamp) column for one of the entries in the table, it considers it as not equal and is inserting it into the table and hence I'm getting repeated values. I'm guessing the WHERE temp_date = '$user1_date'is not working properly. Some troubleshooting that I have done included
Changing '$user1_date' to just $user1_date in the WHERE
statement
Changing the WHERE clause as follows WHERE temp_date = (date)'$user1_date'
It will be great if somebody can help me out with this!
A nice easy solution would be giving temp_date a UNIQUE INDEX in your Mysql Table, as that would not allow the same value to be inserted twice. This would also make your operations more efficient, as you wouldn't have to do SELECT * every time you want to insert something.
However, for what you're doing, I think I see your problem; there are some quirks in your logic so I'll try to dispel them here. (Hopefully?) this will make your program cleaner and you'll be able to pinpoint the error, if not eliminate it altogether.
Examining this piece of code:
// $user1_date doesn't have a value here! //
$user1_date = mysql_real_escape_string($user1_date);
...
$user1_date = date("Y-m-d H:i:s", strtotime($user1_date));
Error 1 - You escape the string before ever setting a value.
What you are doing is that you are using mysql_real_escape_string() before $user1_date is ever defined.
Correction:
// Getting better, but not done. //
$user1_date = date("Y-m-d H:i:s", strtotime($user1_date));
...
$user1_date = mysql_real_escape_string($user1_date);
Error 2 - You do not give the date() function appropriate parameters
The date() function in PHP expects a timestamp, which is just an int. You can easily get the time with time(), so that should rectify your problem
Correction:
// You use strtotime($user1_date), but you should use time() //
$user1_date = date("Y-m-d H:i:s", time());
...
$user1_date = mysql_real_escape_string($user1_date);
These are small mistakes, but they can be deadly. Like I said, you should assign temp_date to a UNIQUE INDEX in your MySQL table, but make sure to correct these errors listed as well.
Let me know how it goes!
I need to know the proper way of doing this.
I have a form where someone can fill in 3 different inputs to update their data.
they can leave one blank if they want and just update the other two or just one. Whatever.
so if i update as:
mysql_query("UPDATE table SET field1=input AND field2=BLANK AND filed3=input WHERE ID=123);
will it leave the blank fields unchanged? just skip over them? or will it replace the field with an empty string/blank field?
If this is the wrong way, what is the correct method?
Thank You!
It will replace them with blank values. The correct way to do it is not to put those items in the query at
all:
if (empty($field1) && empty($field2) && empty($field3) {
// show error message, nothing to do
return;
}
$updates = array();
if (!empty($field1))
$updates[] = 'field1="'.mysql_real_escape_string($field1).'"';
if (!empty($field2))
$updates[] = 'field2="'.mysql_real_escape_string($field2).'"';
if (!empty($field3))
$updates[] = 'field3="'.mysql_real_escape_string($field3).'"';
$updates = implode(', ', $updates);
mysql_query("UPDATE table SET $updates WHERE ID=123");
Obviously it would be cleaner to put the changes in an associative array or object, and then loop through them.
The following UPDATE statement should leave the fields unchanged if the user uses '' as their input, otherwise, it will use the input given to update the field.
UPDATE table
SET field1 = CASE
WHEN input = '' THEN field1
ELSE input
END
, field2 = CASE
WHEN input2 = '' THEN field2
ELSE input2
END
, field3 = CASE
WHEN input3 = '' THEN field3
ELSE input3
END
WHERE ID = 123
This is done with the CASE statement. The WHEN conditions check to see what the input it, and if it is '' (omitted basically) it will use the current value of field1 to update field1 with, basically leaving it unchanged. If there is a value, it will use that new value instead.
If you do not wish to update a certain field you will have to remove the field from your UPDATE statement.
UPDATE table
SET field1=input AND filed3=input
WHERE ID=123