MYSQL/PHP How do I insert a null value? - php

I'm having problems updating records to contain NULL values - in particular, a field which is of type Date.
I'm using prepared statements and I've tried the following:
// Fails
$value = NULL;
// Fails
$value = "";
// Fails
$value = "NULL";
all 3 of the above result in a date of 1969-12-31 being entered (0). How do I insert NULL values?

Did you read the following question/answer: using nulls in a mysqli prepared statement
That seems to be the same issue. Correct me if I'm wrong?

Related

How to update a date value that is blank on MSSQL?

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 ..

Empty DATETIME value stored as 0000-00-00 00:00:00 instead of NULL in MySQL [duplicate]

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().

Values getting rounded up in mysql

So basically if I try to insert a value like 2.22 it will get inserted as 2.00 instead of 2.22. I really have no idea why is this happening. I tried changing type of column in mysql but that didn't help at all.
Column in mysql is set to Decimal(7,2).
Here is how i insert the value to database:
$ks = new ks();
$value = $_POST['value']; //value from input field
$data = $ks->getPrepare("INSERT into enties (amount) VALUES (?)");
$data->bind_param("i", $value);
$data->execute();
I figured it out, if you are trying to add decimal numbers to database with prepared statement, you have to use "d" (for double) instead of "i" in bind_param() function.
Example:
$value = "2.22";
$data->bind_param("i", $value);
Value added to database in this case will be 2.00
Example #2
$value = "2.22";
$data->bind_param("d", $value);
Value added to database in this case will be 2.22

PHP MYSQL - empty variable fails on insert

I have an insert statement that inserts variables collected from a form POST on the previous page. If the variables from the form are not filled in it fails on insert (presumably because it is inserting an empty string...) I have the dataype set to allow NULL values - how do I insert null values if the field was left empty from the form POST?
$query = "
INSERT INTO songs (
userid,
wavURL,
mp3URL,
genre,
songTitle,
BPM
) VALUES (
'$userid',
'$wavFile',
'$mp3File',
'$genre',
'$songTitle',
'$BPM'
)
";
$result = mysql_query($query);
The exact manner depends on if you are writing the query or binding parameters to a prepared statement.
If writing your own, it would look something like this:
$value = empty($_POST['bar']) ? null : $_POST['bar'];
$sql = sprintf('INSERT INTO foo (bar) VALUES (%s)',
$value === null ? 'NULL', "'".mysql_real_escape_string($value)."'");
$result = mysql_query($sql);
The main point is that you need to pass in the string NULL (without quotes) if the value should be null and the string 'val' if the value should be "val". Note that since we are writing string literals in PHP, in both cases there is one more pair of quotes in the source code (this makes one pair in the first case, two pairs in the second).
Warning: When inserting to the database directly from request variables, it is very easy to be wide open to SQL injection attacks. Do not be another victim; read about how to protect yourself and implement one of the universally accepted solutions.
For what I understand when something is not filled the post variable is not set as an empty value but rather not set at all so in php you'd do for example:
$genre = isset($_POST['genre']) ? $_POST['genre'] : NULL;
Here's how I do it. I don't like sending anything to an SQL query right from POST (always sanitize!) in the following cas you just run through the POST vars one by one and assign them to a secondary array while checking for 0 length strings and setting them to NULL.
foreach ($_POST as $key => $value) {
strlen($value)=0 ? $vars[$key] = NULL : $vars[$key] = $value
}
Then you can build your SQL query from the newly created $vars[] array.
As Jon states above, this would be the place to also escape strings, strip code and basically do all your server side validation prior to data being inserted into the db.

passing a null value to mysql database

A user fills out a form and if they choose to not fill out a field that is not required php does this:
if($_SESSION['numofchildren']=="")
$_SESSION['numofchildren']=null;
But when I use the session variable in a mysql query, the result is not null, but is 0. The column is a tinyint(4) that allows NULL.
Why am I getting a 0 instead of NULL?
Probably because PHP doesn't convert 'null' into 'NULL'. You are probably just inserting an empty value.
INSERT INTO TABLE (`Field`) ('')
You probably have the default for the column set to '0', and that means that it will insert a 0 unless you specify a number or NULL
INSERT INTO TABLE ('Field') (NULL)
To fix this, check for Null Values before you do the query.
foreach($values as $key => $value)
{
if($value == null)
{
$values[$key] = "NULL";
}
}
I have a feeling that prepared statements will have the foresight to do this automagically. But, if you are doing inline statements, you need to add a few more things.
MySQL values must have quotes around them, but Nulls don't. Therefore, you are going to need to quote everything else using this
foreach($values as $key => $value)
{
if($value == null)
{
$values[$key] = "NULL";
}
else
{
// Real Escape for Good Measure
$values[$key] = "'" . mysql_real_escape_string($value) . "'";
}
}
Then, when you create the statement, make sure to not put quotes around any values
$SQL = "INSERT INTO TABLE (Field) VALUES(".$values['field'].")";
turns into
$SQL = "INSERT INTO TABLE (Field) VALUES("Test Value")";
or
$SQL = "INSERT INTO TABLE (Field) VALUES(NULL)";
Have a look at the table definition for whichever table you're inserting into. The 'default' value for that field is probably set to zero.
The version of MySql you are using is quite important in determining precisely how MySql treats Data Type Default Values.
The above link says:
For numeric types, the default is 0,
with the exception that for integer or
floating-point types declared with the
AUTO_INCREMENT attribute, the default
is the next value in the sequence.
You all where probably right, but all I had to do is put quotes around the null.
if($_SESSION['numofchildren']=="")
$_SESSION['numofchildren']='NULL';
I had the same problem some minutes ago, but then I figured it out. In my case I was making the query with the NULL variables between quotes like these ", '. Let me explain myself...
This is what you want to do:
INSERT INTO `tbl_name` (`col1`, `col2`) VALUES (NULL,"some_value");
So if you want to use a NULL variable it should be "NULL", like this:
$var1="NULL"; $var2="some_value";
Now, if you want to use $var2, you will type '$var2' in the query, but you shouldn't do the same for $var1:
INSERT INTO `tbl_name` (`col1`, `col2`) VALUES ($var1,'$var2');
If you put $var1 between quotes, you'll get a 0 instead NULL.
For me it didn't work to put NULL var in database, I used var char(2).
So I just made 2 queries. This way it will work 100%. For your example it would be:
if($_SESSION['numofchildren']=="")
{
$updatequery="
UPDATE table
SET table1='$value', table2='$value2', numofchilrdrentable=(NULL)
";
}
else
{
$updatequery="
UPDATE table
SET table1='$value', table2='$value2', numofchilrdrentable='$_SESSION[numofchildren]'
";
}
$updatequeryresult=mysql_query($updatequery) or die("query fout " . mysql_error() );
edit: var char -> var char(2)
null parsed to string becomes 0. Try using is_null() to check that first and place NULL instead of 0 in the query.
Or, try using PDO and PDO::prepare for a perfect and hacker-safe query.
It's very confusing especially when values were posted from a web form. I do it like that:
We assume you need a database field named 'numofchildren' that will accept possible values: NULL, 0, 1, 2.., etc. up to 99 and default should be the SQL NULL value.
SQL field should be defined as:
.. `numofchildren` INT( 2 ) NULL DEFAULT NULL
When you insert your data for the NULL values you pass strings like 'NULL' and look for them when looping the incoming data. The other values you just cast to integers:
foreach ($data as $v) {
$v['numofchildren'] = !isset($v['numofchildren']) || $v['numofchildren'] === 'NULL' ? '(NULL)' : (int) $v['numofchildren'];
$q = "INSERT INTO tablename (numofchildren) VALUES ({$v['numofchildren']}) ";
...
}
Note that {$v['numofchildren']} in SQL query is not surrounded with single quotes because you do not pass strings but integers (0,1,2..) or SQL NULL.
I believe it's clear and short and covers the issue.
if you want set NULL for any column in DATABASE
at first
You should check is_null for that column
secuond :if the variable you want
Set to null code you must insert "null" in double quote then submit to database
If you set null to double quote("") nothing, nothing will be sent and the database will get an error
for example :
function insert_to_db($var){
...
sql="INSERT INTO table VALUES($var)"
...
}
when you use in code with "" and without "" =>
function insert_to_db(null)// error : INSERT INTO table VALUES()
correct:
function insert_to_db("null")//its ok

Categories