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;
}
}
Related
I'm trying to find a smarter way to validate my inputs with PHP. If the array finds an empty field, it has to add a new element to the array and display an error message.
So far, I haven't succeeded.
The code behind
$felter = array();
if(isset($_POST['submit'])) {
$produktnavn = $_POST['produktnavn'];
$kategori = $_POST['kategori'];
if( !empty( $felter ) ) {
foreach ($felter as $felt) {
if ($felter == '') {
$fejl = true;
}
}
}
else {
$sql = "UPDATE produkt SET produkt_navn = '$produktnavn', fk_kategori_id = '$kategori' WHERE produkt_id=$id";
mysqli_query($db, $sql);
echo "Produktet blev opdateret";
}
Input form
<input type="text" class="form-control" name="produktnavn" value="<?php echo $produktnavn; ?>">
The code starts with $felter = array(); which initializes an empty array.
Then, without changing the array itself, you're checking for non-emptiness of $felter
if( !empty( $felter ) ) {
foreach ($felter as $felt) {
if ($felter == '') {
$fejl = true;
}
}
}
You're trying to iterate over an array that has not gotten any elements pushed into it. And the logic statement if( !empty ($felter)) will also not work as expected either.
As a test, before the check for !empty, put something in the array with $felter[] = 'Test word'; and then, underneath it... (if you're looking for a non-empty array, the logical checker could be if(count($felter)) { before iterating over the array with foreach ($felter as $felt) { if ($felt == '')
$felter = array();
$felter[] = 'Test word';
if(isset($_POST['submit'])) {
$produktnavn = $_POST['produktnavn'];
$kategori = $_POST['kategori'];
if( count( $felter ) ) {
foreach ($felter as $felt) {
if ($felt == '') {
$fejl = true;
}
}
}
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.
Look at my script:
if((isset($_POST['unma']) && isset($_POST['livi'])) && (isset($_POST['cont']) &&
isset($_POST['phone']))){
if(
(
(
(
(isset($_POST['fnma']) && isset($_POST['lnma']))
&&
(isset($_POST['occ']) && isset($_POST['hom']))
)
&&
(
(isset($_POST['town']) && isset($_POST['dist']))
&&
(isset($_POST['dispmb']) && isset($_POST['fbc']))
)
)
&&
(
(
(isset($_POST['gp']) && isset($_POST['twt']))
&&
(isset($_POST['ins']) && isset($_POST['flc']))
)
&&
(
(isset($_POST['ile']) && isset($_POST['cam']))
&&
(isset($_POST['cam_co']) && isset($_POST['prof_phr']))
)
)
)
&&
isset($_POST['awards'])
){
// Codes here
}
How can I short this isset functions. I found an solution with foreach but they are not checking the post isset, rather they are checking if the posted values are not empty
You can use
if (isset($_POST['a'], $_POST['b'], $_POST['c'], ...))
and so on. If any of the variables is not set then you will get false.
$expectedKeys = ['fnma', 'lnma', ...];
if (!array_diff_key(array_flip($expectedKeys), $_POST)) {
// all keys are set
}
I think something like this would work:
// add all names of the values that needs to be set in the `$_POST` array
$values = array('fnma', 'lnma');
function checkSet($array) {
foreach($array as $value) {
if(!isset($_POST[$value])) return false;
}
return true;
}
if(checkSet($values)) {
// your code
}
put required fields in a array and check for it using loop,it is easy and easy to add required fields.
$req_values = array('fnma','lnma','occ','hom','town','dist','dispmb','fbc','gp','twt','ins','flc','ile','cam','cam_co','prof_phr');
foreach($req_values as $key) {
if (empty($_POST[$key])) {
echo $key .'is required';
exit;
}
}
Knowing that isset can take multiple values, you could do this:
if (isset($_POST['unma'], $_POST['livi'], $_POST['cont'], $_POST['phone'], $_POST['fnma'], $_POST['lnma'], $_POST['occ'], $_POST['hom'], $_POST['town'], $_POST['dist'], $_POST['dispmb'], $_POST['fbc'], $_POST['gp'], $_POST['tat'], $_POST['ins'], $_POST['flc'], $_POST['ile'], $_POST['cam'], $_POST['cam_co'], $_POST['prof_phr'], $_POST['awards'])) {
// Codes here
}
But that seems nightmarish. I would make the $_POST keys an array & then do the following:
// Set an array of post values.
$post_values = array('unma','livi','cont','phone','fnma','lnma','occ','hom','town','dist','dispmb','fbc','gp','tat','ins','flc','ile','cam','cam_co','prof_phr','awards');
// Set '$post_valid' to an array.
$post_valid = array();
// Roll through the post values.
foreach ($post_values AS $post_key => $post_value) {
// If the value is set, set '$post_valid' to TRUE or else set it to FALSE.
// $post_valid = isset($_POST[$post_key]) ? TRUE : FALSE; // Not really needed. Simple `isset` should work.
$post_valid[$post_key] = !empty($_POST[$post_key]);
}
// Now if '$post_valid' values are all true, do something.
$post_valid_values = array_values($post_valid);
if (!empty($post_valid_values) && (count($post_valid_values) == count($post_values))){
// Codes here
}
I have one cycle while:
while ($userEquipments = mysql_fetch_array($getUserEquipments))
and in this cycle have one if with arrays:
if ($userEquipments['cloth_id'] == $clothes['id'] && $userEquipments['cloth_is_used'] == 1)
$isUsed = array('cloth_type' => $clothes['type_cloth'], 'cloth_name' => $clothes['name'], 'cloth_image' => $clothes['image']);
My question is how to return all information in this arrays?
You should declare your array outside your while, this way you can access it outside the loop.
Try this:
$isUsed[];
while ($userEquipments = mysql_fetch_array($getUserEquipments))
{
if ($userEquipments['cloth_id'] == $clothes['id'] && $userEquipments['cloth_is_used'] == 1)
{
$isUsed['cloth_type'] = $clothes['type_cloth'];
$isUsed['cloth_name'] = $clothes['name'];
...
break;
}
}
// Print the array
print_r($isUsed);
I have these variables, and I need to check if all of them isset(). I feel there has to be a more efficient way of checking them rather than one at a time.
$jdmMethod = $_POST['jdmMethod'];
$cmdMethod = $_POST['cmdMethod'];
$vbsMethod = $_POST['vbsMethod'];
$blankPage = $_POST['blankPage'];
$facebook = $_POST['facebook'];
$tinychat = $_POST['tinychat'];
$runescape = $_POST['runescape'];
$fileUrl = escapeshellcmd($_POST['fileUrl']);
$redirectUrl = escapeshellcmd($_POST['redirectUrl']);
$fileName = escapeshellcmd($_POST['fileName']);
$appData = $_POST['appData'];
$tempData = $_POST['tempData'];
$userProfile = $_POST['userProfile'];
$userName = $_POST['userName'];
Try this
$allOk = true;
$checkVars = array('param', 'param2', …);
foreach($checkVars as $checkVar) {
if(!isset($_POST[$checkVar]) OR !$_POST[$checkVar]) {
$allOk = false;
// break; // if you wish to break the loop
}
}
if(!$allOk) {
// error handling here
}
I like to use a function like this:
// $k is the key
// $d is a default value if it's not set
// $filter is a call back function name for filtering
function check_post($k, $d = false, $filter = false){
$v = array_key_exists($_POST[$k]) ? $_POST[$k] : $d;
return $filter !== false ? call_user_func($filter,$v) : $v;
}
$keys = array("jdmMethod", array("fileUrl", "escapeshellcmd"));
$values = array();
foreach($keys as $k){
if(is_array($k)){
$values[$k[0]] = check_post($k[0],false,$k[1]);
}else{
$values[$k] = check_post($k[0]);
}
}
You could extend the keys array to contain a different default value for each post-value if you wish.
EDIT:
If you want to make sure all of these have a non-default value you could do something like:
if(sizeof(array_filter($values)) == sizeof($keys)){
// Not all of the values are set
}
Something like this:
$jdmMethod = isset($_POST['jdmMethod']) ? $_POST['jdmMethod'] : NULL;
It's Ternary Operator.
I think this should work (not tested, from memory)
function handleEmpty($a, $b) {
if ($b === null) {
return false;
} else {
return true;
}
array_reduce($_POST, "handleEmpty");
Not really. You could make a list of expected fields:
$expected = array(
'jdmMethod',
'cmdMethod',
'fileName'
); // etc...
... then loop those and make sure all the keys are in place.
$valid = true;
foreach ($expected as $ex) {
if (!array_key_exists($ex, $_POST)) {
$valid = false;
break;
}
$_POST[$ex] = sanitize($_POST[$ex]);
}
if (!$valid) {
// handle the problem
}
If you can develop a generic sanitize function, that will help - you can just sanitize each as you loop.
Another thing I like to use is function that gives a default as it sanitizes.
function checkParam($key = false, $default = null, $type = false) {
if ($key === false)
return $default;
$found_option = null;
if (array_key_exists($key,$_REQUEST))
$found_option = $_REQUEST[$key];
if (is_null($found_option))
$found_option = $default;
if ($type !== false) {
if ($type == 'string' && !is_string($found_option))
return $default;
if ($type == 'numeric' && !is_numeric($found_option))
return $default;
if ($type == 'object' && !is_object($found_option))
return $default;
if ($type == 'array' && !is_array($found_option))
return $default;
}
return sanitize($found_option);
}
When a default is possible, you'd not want to do a loop, but rather check for each independently:
$facebook = checkParam('facebook', 'no-facebook', 'string);
It is not the answer you are looking for, but no.
You can create an array an loop through that array to check for a value, but it doesn't get any better than that.
Example:
$postValues = array("appData","tempData",... etc);
foreach($postedValues as $postedValue){
if(isset($_POST[$postedValue])){
...
}
}