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
Related
I keep having problems with quotes in relation to a table update. I'm sending a Post with several values from a form, and then update a table with them. For the code to work, I need to wrap keys with backslash ($ColumnaString), and values with single quotes ($ValueString). This works OK. My problem is that occasionally I want to update to NULL (when $value==""). But my present code don't do that. Can somebody spot the problem?
$id_tag=trim($_POST['id']);
foreach($_POST as $key=>$value){
if ($key!="UpdatePeople"){
$ColumnaString="`".$key."`";
$ValueString="'".iconv('UTF-8', 'ISO-8859-1//TRANSLIT', utf8_encode($value))."'";
if ($key=="In_Date" and $value=="") {$ValueString==NULL;} //Hereis my problem I think
$link->query("UPDATE MyTable SET ".$ColumnaString."=".$ValueString." WHERE `id`=".$id_tag."");
}
}
You could check $id_tag and create a proper part of sql code
$str = ($id_tag ='' ) ? ' is null ' : ' = '.$id_tag;
$link->query("UPDATE MyTable SET ".$ColumnaString." = ".$ValueString." WHERE `id`".str."");
and for $vale
if ($key=="In_Date" and $value=="") { $ValueString = 'NULL' ;} //Hereis my problem I think
check your database if the columns is defined as NOT NULL
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
I want to insert a NULL value into a table column containing the phone area code with the following properties:
mediumint unsigned DEFAULT NULL
In my PHP script, I have this check to convert an empty string to a NULL value:
if($_POST['area_code'] == "") $_POST['area_code'] = NULL;
// clean POST
foreach($_POST as $field => $value)
{
$string[] = $field."=".$value;
}
$sql = "UPDATE Buyer SET ".implode(", ", $string)." WHERE user='$user'";
However, I am getting 0 instead of NULL value. What should I do to insert a NULL?
Your statement needs to look like
UPDATE ... SET area_code = NULL ...
If you're casting a PHP null to a string as you do, it'll just cast to "", i.e. an empty string. You'll need to change the value to "NULL" (the string "NULL") instead of just NULL (the type null). You should also seriously escape/sanitize/validate your values before you plug them into an SQL query, you're wide open for SQL injection.
From http://php.net/manual/en/language.types.string.php
NULL is always converted to an empty string.
when you build $string[], you can't just concatenate your $value, or your nulls will be converted to empty strings, which convert back to zero. You'll have to do a test like:
$value == '' ? 'NULL' : $value
Change PHP NULL to MySQL NULL(string):
if($_POST['area_code'] == '') $_POST['area_code'] = 'NULL';
NULL is always converted to an empty string.
Try
if($_POST['area_code'] == "") $_POST['area_code'] = "NULL";
because null isn't a string
Try it like this:
if($_POST['area_code'] == "") $_POST['area_code'] = "NULL";
For starters, you should be escaping these posted values (maybe you already are). Secondly, NULL in PHP is always converted to an empty string (http://php.net/manual/en/language.types.string.php). Instead, use:
$_POST['area_code'] = 'NULL';
Which will then correctly create the string:
area_code=NULL
for your UPDATE statement.
If your database table column data type is defined as int/float/numeric then it takes 0 instead of NULL. Because what you are doing is, making it as string that does not matches with column definition which was int/float.
That's because you cast your NULL to string:
$field."=".$value
You have two alternatives:
Code an exception for NULL values:
if( is_null($value) ){
$string[] = $field . '=NULL';
}else{
// Please note I've also added proper string escaping
$string[] = $field . "='" . mysql_real_escape_string($value) . "'";
}
Switch to a library that supports prepared statements (IMHO, the simplest and most reliable solution):
$string[] = $field . '=?';
$params[] = $value;
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.
I'm using the WordPress DB interface to insert some nullable row values. The function:
$wpdb->insert( $table, $data, $format );
takes an array of values in the $data param. If I exclude certain field values from the $data array, the fields show up null in the table. However, I want to be able to populate the $data array with values for all the fields, but make those values null when I need to. However, if I pass values that = NULL, the database values are not null, but blank. What should I do?
Looking at the wpdb source code, the "insert" method ends up being mapped into SQL that places every field value between single-quotes (line 1233):
$sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`)
VALUES ('" . implode( "','", $formatted_fields ) . "')";
To insert a real NULL, you need to place an unadorned NULL word into that expression, and it's not allowed for. So what is being inserted is the 4-letter string "NULL".
Note that this method leaves it to the user to be inserting the proper data types and depends on MySQL to automatically convert quoted e.g. numerics into real numeric values.
Looks like the following works:
Instead of:
$nullable_value = NULL;
do:
$nullable_value = mysql_escape_string("NULL");
For explanation see thread answers here and here.
EDIT:
On second glance, this won't work in DB, for the reason #le dorfier states...