What is the difference between value = NULL; and value = ""; in PHP ?
Am facing wierd response as if I set value = ""; than I get empty array response from database which is what am supposed to get but if I set value = NULL; than I get empty string response from mysql database instead of empty array response.
I am not sure why this is the case. Any Suggestions !!!
Have a look at
Working with NULL Values
The NULL value can be surprising until
you get used to it. Conceptually, NULL
means “a missing unknown value” and it
is treated somewhat differently from
other values. To test for NULL, you
cannot use the arithmetic comparison
operators such as =, <, or <>. Use the IS NULL and IS NOT NULL operators instead.
empty strings and NULL are treated differently in MySQL. I had a similar question about this issue:
why use NOT NULL default = ''?
You have 2 solutions here:
Set the database field(s) you are checking to NOT NULL default '' or something similar.
rewrite your queries so that check both cases. ex: 'where field = '' OR field IS NULL'
Value = NULL sets the variable to nothing, basically. Whereas Value = "" sets it to a blank string and while a blank string might look like nothing, it technically is a value of sorts. NULL and "" are both different values.
Related
I have the following which only inserts to column two if the value is empty:
UPDATE name
SET one=?,
two=COALESCE(two, ?),
three=?
WHERE id = ?
However, this only works if column two if the value is null. How can I get this to work if it is either NULL OR an empty string.
It should always insert to one and three. It should only insert to two if it is NULL or empty
I am using SQLite with PHP
If by "empty" you mean an empty string, you can use nullif():
two = COALESCE(NULLIF(two, ''), ?)
The more general solution is a CASE expression.
Don't store empty strings in TEXT columns.
Update the table to replace all empty strings with NULLs:
UPDATE name
SET two = NULL
WHERE TRIM(two) = ''
Now you can use your query, which is correct and in any other query you only need to check for NULL.
I have a simple MySQLi statement with bound results. One of the fields in that recordset is a double and results can be either NULL, 0 or other numeric value.
$wheels_cost is the recordset bound result.
The following logic should ignore null values and only process zero or other numeric values.
if($wheels_cost <> NULL){
carry out a process
} else {
the value is null so ignore
}
For some reason, the results I'm getting seem to reflect that the result is a zero rather than a null - which is not the desired result.
I've checked the DB and the field is null.
I need to tell the difference between a null and a zero value.
I've only tried the above logic and can't think why it doesn't work. Should I be using isset() or is_null() or empty()?
Thanks for feedback
Finished code below:
if(!is_null($wheels_cost)){
carry out a process
} else {
the value is null so ignore
}
Worked perfectly
Try this:
if($wheels_cost is not NULL){
# carry out a process
} else {
# the value is null so ignore
}
I do not use mySQLi but I think the syntax should look like PostGreSQL
In PostGreSQL, the NULL value can not be equal or differentiated to any column or variable, since it is an unknown value and of an unknown type.
Examples here: https://www.techonthenet.com/mysql/is_null.php
I'm selecting a couple of values from a mysql database, combining and hashing them. Sometimes the result is null. Anyone know why?
First we fetch an associative array representing the row.
$results = dal::query("select foo, email from wtf where email = ?", $_GET["email"], "row");
Then we check for truthy results and hash.
if($results["foo"] && $results["email"]){
$whyisthisnullsometimes = md5($results["foo"] . $results["email"]);
$url = "https://example.com/dostuff.php?thing={$whyisthisnullsometimes}";
}
$whyisthisnullsometimes occasionally is just null. Not sure why.
The url is appended to an email message and sent. Users are hitting this link, which would not exist if ($results["foo"] && $results["email"]) evaluates to false.
wtf.foo is char 32 and wtf.email is varchar 250. collation is latin1_swedish_ci
That is quick answer:
when
if($results["foo"] && $results["email"]){
your condition is false you have $whyisthisnullsometimes not defined and php interprets it as null.
For further information you should post bigger fragment of your code :-)
I have searched the site and although I have found questions and answers similar I haven't been able to find an answer. After 4 hours of searching I've decided to bite the bullet and ask the question.
I have 4 date fields in a form that aren't required. I would like it to enter a date into the database if one of the fields has an entry or null if any are left blank.
I have an if statement that checks if the value is empty and if so $value = null, otherwise use $value = date("Y-m-d",strtotime($_post['value'])) to convert it to a date and this works well.
The problem is in my query. If I use '$value' it will insert the date correctly but won't insert a null value because using 'null' makes sql think it's a string. If I use just $value the null inserts just fine but the date goes in as 0000-00-00.
Any advice would be very much appreciated
Thanks for the advice so far...
Null is allowed, this is my script...
if(empty($_POST['fp32_original_install_date'])){
$fp32_install = NULL;
}else{
$fp32_install = date("Y-m-d",strtotime($_POST['fp32_original_install_date']));
}
$sql = "INSERT INTO accounts_cstm (id_c, support_c, install_date_c, sware_renewal_date_c, product_key_c, account_status_c, fp32_support_type_c, fp32_support_renewal_date_c, fp32_original_install_date_c) VALUES ('$Guid','$cdr_support', '$cdr_install', '$cdr_renew', '$prod_key', '$account_status', '$fp32_support', '$fp32_renew', $fp32_install)";
If I use in the query $fp32_install a null value goes in just fine but a date goes in as 0000-00-00, if I use '$fp32_install' the date goes in fine but a NULL value goes in as 1970-01-01 (probably because it sees 'NULL' as a string)
If I echo $fp32_install the value is shown as 2012-08-16 and the SQL type for the column is date and the default is NULL
If you are using posted values from a form, then $_POST['value'] will not be NULL.
You should check for empty values instead.
if($_POST['value']=="")
{
$value="NULL";
}
else
{
$value="'".date("Y-m-d",strtotime($_POST['value']))."'";
}
From the behavior you describe, it sounds as if your DATE column is defined with a DEFAULT 0 clause, or you are providing an invalid value.
According to the MySQL documentation:
<snip>
Invalid DATE, DATETIME, or TIMESTAMP values are converted to the “zero” value of the appropriate type ('0000-00-00' or '0000-00-00 00:00:00').
</snip>
It's difficult to diagnose the exact problem without seeing example code. As a starter, I suggest you try echoing out the SQL statement that is being sent to the database.
I have a strong suspicion that the value for the DATE column is going to appear with quotes around it, a string value of 'NULL', rather than the bare keyword NULL.
I have a MYSQL table with an ENUM field named "offset" and some other columns. The field is defined as:
ENUM(0,1), can be NULL, predefined value NULL
Now I have two server. A production server and a development server and the same PHP script used to create and to update the database.
First step: the application create the record witout passing the "offset" in the CREATE query.
Second step: the application ask to the user some data (not the "offset" value), read the row inserted in step one and make an array, update some field (not the "offset" field), create a query in an automated fashion and save the row again with the updated values.
The automated query builder simple read all the field passed in an array and create the UPDATE string.
In both systems I obtain this array:
$values = array(... 'offset' => null);
and convert it in this same query passing the values in the mysql_real_escape_string:
UPDATE MyTable SET values..., `offset` = '' WHERE id = '10';
Now there is the problem. When i launch the query in the production system, the row is saved, in the development system I got an error and the db says that the offset data is wrong without saving the row.
From phpmyadmin when I create the row with the first step, it shows NULL in the offset field. After saving the field in the system which give no errors, it show me an empty string.
Both system are using MySQL 5 but the production uses 5.0.51 on Linux and development use 5.0.37 on Windows.
The questions:
Why one system give me an error an the other one save the field ? Is a configuration difference ?
Why when I save the field which is an enum "0" or "1" it saves "" and not NULL ?
Why one system give me an error an the other one save the field ? Is a configuration difference ?
Probably. See below.
Why when I save the field which is an enum "0" or "1" it saves "" and not NULL ?
According to the MySQL ENUM documentation:
The value may also be the empty string ('') or NULL under certain circumstances:
If you insert an invalid value into an ENUM (that is, a string not present in the list of permitted values), the empty string is inserted instead as a special error value. This string can be distinguished from a "normal" empty string by the fact that this string has the numeric value 0. ...
If strict SQL mode is enabled, attempts to insert invalid ENUM values result in an error.
(Emphasis added.)
strager's answer seems like a good explanation on why your code behaves differently on the 2 environments.
The problem lies elsewhere though. If you want to set a value to NULL in the query you shound use exactly NULL, but you are using mysql_real_escape_string() which result is always a string:
$ php -r 'var_dump(mysql_real_escape_string(null));'
string(0) ""
You should handle this differently. E.g:
$value = null
$escaped_value = is_null($value) ? "NULL" : mysql_real_escape_string($value);
var_dump($escaped_value);
// NULL
Some DB layers, like PDO, handle this just fine for you.
If you want it to be NULL, why don't you do this in the first place:
UPDATE MyTable SET values..., `offset` = NULL WHERE id = 10;