$record['field'] = null;
if (isset($record['field']) || is_null($record['field'])) {
// When $record['field'] is set and not null, OR, when $record['field'] = null
// Basically, when $record['field'] is defined as $record['field'] = whatever, even null.
} else {
// When $record['field'] is not defined at all, not even null
}
My intention is to check if $record['field'] is defined at all, even null.
However every time $record['field'] is not set at all (e.g. comment out $record['field'] = null;), it gives me this error:
Undefined index: field
In case anyone would ask, this is for when NULL values become meaningful, such as in a SQL query assigning a NULL value to a timestamp column would make MySQL update it with the current timestamp.
Any way I can do this?
Since what you have here is not just a variable but an associative array, you can use array_key_exists() to check that the array contains a field with that name, regardless of its value.
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
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 have some records stored through Parse PHP SDK.
Among the fields there is a Date field which is initialized with an undefined value.
On the go this value may change either to a real date or a null value, in case I set a date and then want to "unset" it. What I am doing is setting it as null.
The problem is that when I want to filter the set dates and all the others (in my case both undefined and null values should be the same, i.e. "unset") I try a query filter similar to the following:
$query->equalTo("mydatefield", NULL);
The weird thing about it is that it only returns the undefined values, not the NULL ones.
On the other hand when I use
$query->notEqualTo("mydatefield", NULL);
the desired records are all returned just fine.
Any idea how to accomplish getting both null and undefined values?
Thanks in advance.
You are correct, it doesn't seem to work with the PHP library. The same thing works fine with the Javascript library.
You can accomplish what you want though by excluding the values that are not null (or undefined). Here is an example:
use Parse\ParseQuery;
//fetch objectIds of all data that is not null
$query = new ParseQuery("tabledata");
$query = $query -> notEqualTo("mydatefield", null);
$results = $query -> find();
$keys = array();
for ($i=0; $i<count($results); $i++){
array_push($keys, $results[$i]-> getObjectId());
}
//now fetch all records but the records with the null column
$query2 = new ParseQuery("tabledata");
$query2 = $query2 -> notContainedIn("objectId", $keys);
$results2 = $query2 -> find();
You can filter queries with null fields with exists and doesNotExist methods of ParseQuery class.
$query->exists("mydatefield"); // returns rows that do not have null value for mydatefield key.
$query->doesNotExist("mydatefield"); // returns rows that have null value for mydatefield key.
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
When performing UPDATE and INSERT queries using Zend_Db, I frequently need to set values equal to NULL (not ''). However, the default behavior of Zend_Db::insert() and Zend_Db::update() seems to be that values that are empty are translated into empty strings ('') and put into the database as such.
Does anyone know of way to actually force a NULL value to go into fields if the value is empty in php?
Try setting the affected fields to: new Zend_Db_Expr('NULL')
I've always just been able to do this using PHP's null:
$toUpdate = array('nullValue' => null, 'otherValue' => 'something');
Zend_Db::update($table, $toUpdate, $where);
As Johrn I was able to do this with PHP's null value:
$value = null;
$what = array($columnName => $value);
$where = $this->_dbTableName->getAdapter()->quoteInto('Id = ?', $dbRecord->Id);
$this->_dbTableName->update($what, $where);
but encountered situations where the database itself had the column set to NOT NULL and in such cases the value was indeed converted to either empty string or in case of FLOATs to 0.00. I guess INT column would end up as 0 ;-)
While using Zend 2.4.7 for those who may be visiting this issue, I was able to use this with William Lannen's answer providing some inspiration. Assuming getTable() returns a Zend\Db\TableGateway object:
public function fetch()
{
$data['column_name1 = ?'] = 'column_value';
$data[] = new \Zend\Db\Sql\Predicate\IsNull('column_name2');
$resultSet = $this->getTable()->select($data);
if (0 === count($resultSet) {
return 'SomeExpectationOrException';
} else {
return $resultSet;
}
}