How to send "null" or empty value to database through PHP? - php

I have a jqgrid that with date columns that post in format 0/0/0000 or if empty send "null" to my php file to then insert to MYsql column. It posts "null" but does not send "null" command to database column. What I'm I missing? Firephp says that at this point my date column inputs are all '"1969-12-31"'. What can I do to post "null" correctly to these columns?
****UPDATE: Here is the var dumb for $_REQUEST:****
array(12) {
["name"]=>string(24) "FABTECH B2B Presentation"
["id_continent"]=>string(6) " Ramon"
["lastvisit"]=>string(10) "12/31/2104"
["cdate"]=>string(9) "8/22/2014"
["ddate"]=>string(9) "9/14/2014"
["notes"]=>string(69) "B2B machines are C1 AJ and HG ATC. Waiting for part data from Yoshi."
["hello"]=>string(2) "No"
["mydate"]=>string(4) "null"
["oper"]=>string(4) "edit"
["id"]=>string(3) "184"
["PHPSESSID"]=>string(32) "93de884f9e02d507ff3662f63149f9f3"
["SQLiteManager_currentLangue"]=>string(2) "10"
}
My code:
$crudColumns = array(
'id' =>'id'
,'name'=>'name'
,'id_continent'=>'id_continent'
,'lastvisit'=>'lastvisit'
,'cdate'=>'cdate'
,'ddate'=>'ddate'
,'notes'=>'notes'
,'hello'=>'hello'
,'mydate'=>'mydate'
);
function fnCleanInputVar($string){
//$string = mysql_real_escape_string($string);
return $string;
}
/*----====|| GET and CLEAN THE POST VARIABLES ||====----*/
foreach ($postConfig as $key => $value){
if(isset($_REQUEST[$value])){
$postConfig[$key] = fnCleanInputVar($_REQUEST[$value]);
}
}
foreach ($crudColumns as $key => $value){
if(isset($_REQUEST[$key])){
if ($key == 'lastvisit' || $key == 'cdate' || $key == 'ddate' || $key == 'mydate' ) {
$crudColumnValues[$key] = '"'.date('Y-m-d', strtotime($_REQUEST[$key])).'"';
} else {
$crudColumnValues[$key] = '"'.fnCleanInputVar($_REQUEST[$key]).'"';
}
}
}
FB::info($crudColumnValues, "Dates");
/*----====|| INPUT VARIABLES ARE CLEAN AND CAN BE USED IN QUERIES||====----*/
Mysql query
case $crudConfig['update']:
/* ----====|| ACTION = UPDATE ||====----*/
if($DEBUGMODE == 1){$firephp->info('UPDATE','action');}
$sql = 'update '.$crudTableName.' set ';
/* create all of the update statements */
foreach($crudColumns as $key => $value){ $updateArray[$key] = $value.'='.$crudColumnValues[$key]; };
$sql .= implode(',',$updateArray);
/* add any additonal update statements here */
$sql .= ' where id = '.$crudColumnValues['id'];
if($DEBUGMODE == 1){$firephp->info($sql,'query');}
mysql_query( $sql )
or die($firephp->error('Couldn t execute query.'.mysql_error()));
break;

Check whether the parameter from the grid is null, and put NULL into the database instead of the date.
foreach ($crudColumns as $key => $value){
if(isset($_REQUEST[$key])){
if ($key == 'lastvisit' || $key == 'cdate' || $key == 'ddate' || $key == 'mydate' ) {
if ($_REQUEST[$key] == 'null') {
$crudColumnValues[$key] = 'NULL';
} else {
$crudColumnValues[$key] = '"'.date('Y-m-d', strtotime($_REQUEST[$key])).'"';
}
} else {
$crudColumnValues[$key] = '"'.fnCleanInputVar($_REQUEST[$key]).'"';
}
}
}

Seems that you may be confusing empty with null. An empty string will be interpreted as "" whereas null will be interpreted as "null", big difference. Try this.
EDIT:
After looking at the PHP manual it seems that if you try to add a null value to an array key it is changed to "".
First of all, create your array like this
['mydate'] => ''
Change your date formatting.
foreach ($crudColumns as $key => $value){
if(isset($_REQUEST[$key])){
if ($key == 'lastvisit' || $key == 'cdate' || $key == 'ddate' || $key == 'mydate' ) {
if (strtotime($value)) {
$value = '"'.date('Y-m-d', $value).'"';
} else {
$value = "";
}
} else {
$crudColumnValues[$key] = fnCleanInputVar($_REQUEST[$key]);
}
Also, part of the issue is that you are specifying the keys but you need to be changing the value.

Related

Fill array regardless if there is empty check

So I have the following code:
if ($obj->updated_date > $record->updated_date || $mode === 'refresh') {
if (empty($obj->birthday) || $obj->hire_date) {
$record->fill([
'birthday' => '',
'hire_date' => ''
]);
} else {
$record->fill($arr);
}
} else {
$record->timestamps = false;
}
Where I'm checking if $obj->birthday or $obj->hire_date is empty, and then define them as empty strings, but here is the problem.
I want to be able to call $record->fill($arr) regardless and prepopulate all my fields on the empty check, but for some reason I can't seem to figure out out.
So heres the logic:
Empty hire_date? set as ''.
Empty birthday? set as ''.
Populate the rest of the fields..
Both hire_date and birthday not empty? Populate all fields.
You can try this:
if ($obj->updated_date > $record->updated_date || $mode === 'refresh') {
$filllArray = $arr;
if (empty($obj->birthday) {
$record->fill([
'birthday' => ''
]);
unset($filllArray['birthday']);
}
if (empty($obj->hire_date)) {
$record->fill([
'hire_date' => ''
]);
unset($filllArray['hire_date']);
}
$record->fill($filllArray);
} else {
$record->timestamps = false;
}
Update 1: Copy the $arr to $filllArray and update the new array to determine what should be filled or not.
I know you've accepted an answer. This is a slightly different way of achieving the same thing (If I understood the question correctly)
if ($obj->updated_date > $record->updated_date || $mode === 'refresh') {
$fa = [];
empty($obj->birthday) ? $fa['birthday'] = '' : $fa['birthday'] = $obj->birthday;
empty($obj->hire_date) ? $fa['hire_date'] = '' : $fa['hire_date'] = $obj->hire_date;
$merged_arr = array_merge($arr, $fa);
$record->fill($merged_arr);
} else {
$record->timestamps = false;
}

Display static message for empty values

i tried below code to fetch results of column dpaid_status from mysql database & its working fine:
Database
site
$i = 0;
foreach($order as $orderData)
{
$k = 0;
$orderitems = $orderData['dproduct_id'];
$orderitemsarray = explode(",", $orderitems);
while ($k < count($orderitemsarray))
{
if ($orderitemsarray[$k] != '0')
{
$stmtorders = $user_home->runQuery("SELECT * FROM order_details");
$stmtorders->execute(array(":dorder_id" => $orderData['entity_id']));
$roworders = $stmtorders->fetch(PDO::FETCH_ASSOC);
$dorderStatus = $roworders['dpaid_status'];
$productdetail = Mage::getModel('catalog/product')->load($orderitemsarray[$k]);
$designer_id = $productdetail->getDesignerID() ;
if($accountType == "admin")
{
$designerName = getDesignerName($productdetail->getDesignerID()) . " -(" . $productdetail->getDesignerID() . ")";
$stmt1 = $user_home->runQuery("SELECT * FROM order_details WHERE dproduct_id=:pid and designerorder_id=:doid");
$stmt1->execute(array(
":doid" => $orderData->getIncrementId(),
":pid" => $orderitemsarray[$k],
));
$paid_status='';
while($datas = $stmt1->fetch())
{
$paid_status=$datas['dpaid_status'];
}
$responce[] = array(
$paid_status
);
return json_encode($responce);
But for some columns there is no value for dpaid_status, so i wanted to display none for those in page. so instead of $paid_status=$datas['dpaid_status']; i tried below code ,
if ($roworders['dorder_id'] == '')
{
$paid_status='unpaid';
}
else
{
$paid_status=$datas['dpaid_status'];
}
ex : in above image there is no row for "15585" in database , so it should display unpaid for that.... but now its displaying blank....
You should check your $paid_status variable right before returning/using it. This way you will catch all cases when the value is empty (either empty value in the table or missing row in the database table).
I have added the new lines to your code, below:
$stmt1 = $user_home->runQuery("SELECT * FROM order_details WHERE dproduct_id=:pid and designerorder_id=:doid");
$stmt1->execute(array(
":doid" => $orderData->getIncrementId(),
":pid" => $orderitemsarray[$k],
));
$paid_status='';
while($datas = $stmt1->fetch())
{
$paid_status=$datas['dpaid_status'];
}
//added new lines of code here - START
if ( $paid_status == ''){
$paid_status='unpaid';
}
//added new lines of code here - END
$responce[] = array(
$paid_status
);
You can solve the problem also at SQL level, just using a query like:
SELECT [field_list], IFNULL(dpaid_status, 'unpaid') as paid_status FROM order_details
which return the dpaid_status value if the field is not null, else return 'unpaid'
You just need to use PHP empty().
Determine whether a variable is considered to be empty. A variable is
considered empty if it does not exist or if its value equals FALSE.
empty() does not generate a warning if the variable does not exist.
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
so your if statement can be written
if (empty($roworders['dpaid_status']))
{
$paid_status='unpaid';
}
else
{
$paid_status=$datas['dpaid_status'];
}
if ($roworders['dpaid_status'] != '')
{
$paid_status=$datas['dpaid_status'];
}
else
{
$paid_status='unpaid';
}

Compare two json file with empty value

I have two json file, and need to sync them, if changes found, below is my json file,
is parent(P) and
another one
is child(C),
Here is my code :
foreach ($localJson->PushNotification as $key => $data ) {
foreach ($this->news as $news ) {
if($news->pushMessageId == $data->pushMessageId){
if($news->Image != "" && $news->Image != $data->Image){
echo "new image found <br />";
}
if($news->documentFile != "" && $news->documentFile != $data->documentFile){
echo "new documentFile found <br />";
}
if($news->categoryIcon != "" && $news->categoryIcon != $data->categoryIcon){
echo "new categoryIcon found <br />";
}
}
}
}
The Problem is everytime when it loops, it doesent discard previous loops value, if current found to be empty
For Ex: 1st loop 1653 pushMessageId compares pdf and updates in child, but for next pushMessageId again it takes same pdf to compare, rather then taking empty field.
I have check your code , its look a simple logical condition and need to update current objects new value.
foreach ($localJson->PushNotification as $key => $data ) {
foreach ($this->news as $news ) {
if($news->pushMessageId == $data->pushMessageId){
if($news->Image != "" && $news->Image != $data->Image){
$data->Image = $news->Image;
}
if($news->documentFile != "" && $news->documentFile != $data->documentFile){
$data->documentFile = $news->documentFile;
}
if($news->categoryIcon != "" && $news->categoryIcon != $data->categoryIcon){
$data->categoryIcon = $news->categoryIcon;
}
}
}
}
I hope this solution may work for you.

How to simplify this code?

I'm just wondering if there's a way to simplify this code?
foreach ($parent_data as $ind_port_record) {
if ( isset($ind_port_record['port_name']) && (strtoupper($ind_port_record['port_name']) == 'GI/2' || strtoupper($ind_port_record['port_name']) == 'G2' || strtoupper($ind_port_record['port_name']) == 'GI2') ){
$record_to_include['remote_id'] = $ind_port_record['remote_id'];
$record_to_include['remote_name'] = $ind_port_record['remote_name'];
$record_to_include['remote_object_id'] = $ind_port_record['remote_object_id'];
$record_to_include['remote_object_name'] = $ind_port_record['remote_object_name'];
break;
}
}
//make sure you have something in remote object details
if ( ! isset($record_to_include['remote_id']) ){
$record_to_include['remote_id'] = '';
$record_to_include['remote_name'] = '';
$record_to_include['remote_object_id'] = '';
$record_to_include['remote_object_name'] = '';
}
I just need to make sure the values inside the $record _to_include are not uninitialized or NULL.
Thanks.
First off, simplify the if()
You currently have a lot of conditions
(strtoupper($ind_port_record['port_name']) == 'GI/2' || strtoupper($ind_port_record['port_name']) == 'G2' || strtoupper($ind_port_record['port_name']) == 'GI2')
Let's make that check an array
in_array( strtoupper($ind_port_record['port_name'], array('GI/2','G2','GI2')) )
Now to check if $record_to_include are not uninitialized or NULL
Let's loop through the array and do a simple check.
foreach($record_to_include as $record => $value) {
$record_to_include[$record] = is_null($value) OR !isset($record_to_include[$record]) ? '' : $value;
}
$record = array_filter($parentData, function (array $record) {
return isset($record['port_name']) && preg_match('!^(GI/2|G2|GI2)$!i', $record['port_name']);
});
$recordToInclude = $record ? current($record) : array(
'remote_id' => null,
'remote_name' => null,
'remote_object_id' => null,
'remote_object_name' => null
);
$gi_constraint = array('GI/2', 'G2', 'GI2'); // you are checking one and the same variable for different values, so you can use in_array here
foreach ($parent_data as $ind_port_record) {
if (isset($ind_port_record['port_name']) && in_array(strtoupper($ind_port_record['port_name']), $gi_constraint)){
foreach ($ind_port_record as $k=>$v) {
$record_to_include[$k] = $v; // as they have the same keys, you can specify the key and assign to the value of $in_port_record
}
break;
}
}
//make sure you have something in remote object details
if (!isset($record_to_include['remote_id']) ){
foreach ($record_to_include as $k => &$v) {
$v = ''; // when using reference, it will change the original array
}
}
Explanations in the code
Try
$arr = array('remote_id','remote_name','remote_object_id','remote_object_name');
if ( isset($ind_port_record['port_name']) && (strtoupper($ind_port_record['port_name']) == 'GI/2' || strtoupper($ind_port_record['port_name']) == 'G2' || strtoupper($ind_port_record['port_name']) == 'GI2') ){
foreach($arr as $ar){
$record_to_include[$ar] = (isset($ind_port_record[$ar]) && isset($record_to_include['remote_id']))?$ind_port_record[$ar]:NULL;
}
}

how to insert a string in database if value is null

In my bind parameters, I am trying to insert answers for each question. I have a simple question which is asking that if a question has no answer, how can I insert the word No Answer in its place in the db? This is because at the moment it will not insert any rows are where the answer is NULL. It only does insert if the question has at minimum one answer
Below is attempt:
$results = $_POST['value'];
foreach($results as $id => $value)
{
$answer = $value;
$quesid = $question_ids[$id];
if($answer = ''){
$answer = 'No Answer';
}
foreach($value as $answer)
{
$insertanswer->bind_param("is", $quesid, $answer);
$insertanswer->execute();
if ($insertanswer->errno) {
// Handle query error here
echo __LINE__.': '.$insertanswer->error;
break 7;
}
}
}
If it is a text input then if($answer == '' || $answer === null){, if it i from a drop down menu then retrive the value: if($answer == ''){ //'' is whatever the value is for this option
Checking if its empty is not enough, you should check for null just incase!
//Take notice of === (Identical operator)
if($answer == '' || $answer === null){
$answer = 'No Answer';
}
its looks like you are using assignment operator (=) in if condition i think it should be comparison operator (==)
if($answer = ''){
$answer = 'No Answer';
}
should be
if($answer == ''){
$answer = 'No Answer';
}
or
if(trim($answer) == '')
or
if(empty($answer)){
also if you want to make sure that $question_ids[$id] is int you can use
$quesid = (int)$question_ids[$id];

Categories