I know that this question has been asked before. I found the post, however, it did not solve my problem as my column does allow null.
I want to insert a NULL value into my integer column.
if ($startYear == "") {
$startYear = NULL;
}
mysqli_query($con, "INSERT INTO Application (startYear) VALUES ('".$startYear."')");
Before you ask, I have checked if $startYear is ever empty, and it is, so this should work.
When I run this query it inputs a 0 into the database row. It does not insert NULL like I want.
Here is my column's structure:
http://i.imgur.com/XuWq9Km.png
One important thing is that, I can not modify the column's structure. It is off limits.
Thanks in advance.
The issue is you're not actually inserting into the query the string 'NULL', but a php null, which makes your query insert empty string, this gets coverted to 0 in the DB.
You'd need to do this:
mysqli_query($con, "INSERT INTO Application (startYear) VALUES (NULL)");
you're inserting a PHP null value, which when used in a string context becomes an empty string - which is what was originally. You have to insert a literal string with the letters n, u,l,l` for this to work:
if ($startYear == '') {
$startYear = 'NULL'; // string null
}
$sql = "INSERT ..... VALUES ($startYear)";
which would produce
INSERT ... VALUES (NULL)
To expand:
$foo = null; // actual PHP null value
$bar = "$foo"; // insert this php null into a string
echo strlen($bar); // returns 0
$foo = 'null' // string with 4 letters: n,u,l,l
$bar = "$foo";
echo strlen($bar); // returns 4
Related
In a script I receive a variable value with GET request and I have to explode it by a delimiter but sometimes part of the string is empty. How do I declare that in the INSERT query to insert NULL if string is empty?
$statement = $db->prepare('insert into _table (column1, column2, etc.) values (?, ?, etc.)
if (isset($_GET['var']) || isset($_GET['var1'])) {
$pieces=explode("delimeter", $var);
// $data = array($somevar, $someothervar, $pieces[0], pieces[1], etc.);
} else {
// other things to do with // $data = array($somevar, $someothervar, etc.);
}
$statement->execute($data);
Sometimes it happens that the value of $pieces[0], $pieces[1], etc is "" (quote excluded, just for reference), or so to say empty. How do I make it insert NULL in the database if any of the exploded pieces are empty? Not really sure where and how to declare the !empty check because of the isset. Current code enters blanks in the table rows instead of NULL for the empty exploded pieces. Please note that the exploded pieces are not always empty and sometimes not all of them are empty, sometimes all are empty. Depends on the case. :)
This should answer your question.
Just set the value you want to insert and be NULL to null e.g $someVar = null;
In your example you might want to check if any of the values in your array are an empty string and replace them with null
foreach ($data as $key => $value) {
if $value === "" {
$data[$key] = null;
}
}
On my page I have a few textboxes and two of those, first name and last name, are not required. If nothing is entered in one or both of those fields I need to insert NULL as nothing rather than NULL as a string value. Currently it is entering them as string values. What do I need to do so it inserts NULL values instead of a string?
PHP Code
<?php
// SQL connection and other variables...
if (!empty($_POST['firstname'])) {
$firstname = $_POST['firstname'];
} else {
$firstname = 'NULL';
}
if (!empty($_POST['lastname'])) {
$lastname = $_POST['lastname'];
} else {
$lastname = 'NULL';
}
$sp = "exec sp_test_proc '$street1', '$street2', '$firstname', '$lastname'";
$res = odbc_exec($conn, $sp);
?>
If I pass in NULL instead of the variable for either of the parameters it works fine. Not sure what is causing the issue by using a variable.
Write NULL instead of 'NULL'
You're making it a string by using quotes.
You need to pass NULL as unquoted string. This is because you are building plain SQL.
So make sure the statement is valid one.
For parameterized query it should be NULL value instead of NULL string.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Insert NULL variable into database
I have a table (log) with Columns:
Seconds: bigint(20) UNSIGNED NULL
IPAddress: varchar(15) NULL
The problem is that whenever the variables are given the value NULL, they are inserted in the columns as an empty string for the IPAddress column and as 0 for the Seconds column, not as NULL.
//PHP 5.3.9//
if(isset($_POST['sec']))
$seconds = mysql_real_escape_string($_POST['sec']);
else
$seconds = NULL;
if(isset($_POST['ip']))
$ipaddress = mysql_real_escape_string($_POST['ip']);
else
$ipaddress = NULL;
$query = mysql_query("INSERT INTO log (Seconds, IPAddress) VALUES('".$seconds."', '".$ipaddress."')", $DbConnectionMyDb);
I've searched all over google, but all the answers assumes that I already know whether the variables $sec and $ip are going to be NULL or not. In my case it depends on the POST data.
Any help is deeply appreciated.
Thanks.
"" !== NULL
"NULL" !== NULL
NULL === NULL
You are inserting ""
At the moment you combine your variables to a string, the NULL value in the variable is casted to an empty string. You need to construct your query that it actually reads:
VALUES (NULL, NULL)
and not
VALUES ("", "")
which you can do by perhaps:
if (is_null($seconds)) $seconds='NULL'; else $seconds='"'.$seconds.'"';
if (is_null($ipaddress)) $ipaddress='NULL'; else $ipaddress='"'.$ipaddress.'"';
$query = mysql_query("... VALUES(".$seconds.", ".$ipaddress.")", ...);
However, using some kind of database library or PDO with prepared statements, which abstracts away these kinds of tasks, would be better in the long run.
I am trying to pass a few NULL values to a stroed procedure but PHP always retains the varaibles to be empty strings '' and not NULL.
My DB insert function looks like this. (I am using a Framework and ADODB so if it looks weird thats why).
function insert_emp($f_name, $last_name, $dob) {
if(!isset($dob)){
$dob = NULL;
}
$this->DB->setConnection("CALL insert_emp('$f_name', '$l_name', '$dob')");
}
I have ensured that $dob is being passed an empty string ''. But for some reason when it calls the stored proc it is not changed to NULL. dob is a datetime field and mysql complains that you can not enter an empty string as a DATETIME. If I hard code the insert such as this
$this->DB->setConnection("CALL insert_emp('Test1', 'Test2', 'NULL')");
it will work. Thanks for the help.
NULL cannot be represented as a string. So you should use a string literal null.
function insert_emp($f_name, $last_name, $dob = 'NULL') {
$this->DB->setConnection("CALL insert_emp('$f_name', '$l_name', '$dob')");
}
I have set it as default value, and it should do what you wanted in the first place.
try this
$this->DB->setConnection("CALL insert_emp('Test1', 'Test2', '')");
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