How to assign a role to a user PHP - php

Well I have this form that adds user, admin.I've given to user the right to add another user but not add an admin or so!
$roles = db_fetch_all("role") ;
$TabRoles = array(''=>'-- Choose --');
foreach($roles as $value)
{
$TabRoles[$value['rid']] = $value['name'];
}
and with print_array($TabRoles); it displays me :
Array
(
[] => -- Choose --
[admin] => Admin
[seo] => SEO
[user] => User
)
The condistion is if (user('rid') == 'admin'|'seo') . I tried this :
foreach($roles as $value)
{
if (user('rid') == 'admin'|'seo')
{
$TabRoles[$value['rid']] = $value['name'];
}else{
$TabRoles[$value['rid']] = $value['name'][2];
}
}
But it displays me the position "2" of the array !
Array
(
[] => -- Choose --
[admin] => m
[seo] => O
[user] => e
)
I want it to display like this :
Array
(
[] => -- Choose --
[user] => User
)
Any solution for this ? Many Thanks!
The solution : thanks to #DanFromGermany:
foreach($roles as $value)
{
if (user('rid') == 'admin' || user('rid') == 'seo')
{
$TabRoles[$value['rid']] = $value['name'];
}elseif (user('rid') == $value['rid']){
$TabRoles[$value['rid']] = $value['name'];
}
}

if (user('rid') == 'admin'|'seo')
| is a bitwise operator, but I guess you want a logical comparison here:
if (user('rid') == 'admin' || user('rid') == 'seo')
Explanation on using array brackets on strings:
$test = 'abcd';
echo $test[0]; // prints a
echo $test[1]; // prints b
echo $test[2]; // prints c
That's why you get only a letter instead of the element you want.
I think you are looking for something like:
foreach($roles as $value) {
if (user('rid') == $value['rid'])
$TabRoles[$value['rid']] = $value['name'];
}
}
or
foreach($roles as $value) {
$TabRoles[$value['rid']] = $value['name'];
}
if (user('rid') != 'seo' && user('rid') != 'admin')) { // inverse/negate the logic!
unset($TabRoles['seo']);
unset($TabRoles['admin']);
}

Related

Choosing 3 biggest numbers from many variables and use the values to echo appropriate reaction

I am trying to pull the 3 biggest numbers from a set of variables. The variables are pulled from a database and are different for every class of students.
I want to distinguish 3 topics that require improvement for each class of students. Here is an example that shows how I do it. The problem is, as long as this is partially working (can distinguish 3 highest values), it fails my expectations when one of the $reg variables is the same as another one. How can I include this option?
$highest1=0;
for ($i=1; $i<=7; $i++) {
if ($highest1<=${"reg$i"}) {
$highest1 = ${"reg$i"};
}
}
$highest2=0;
for ($i=1; $i<=7; $i++) {
if ($highest2<=${"reg$i"} && ${"reg$i"}!=$highest1) {
$highest2 = ${"reg$i"};
}
}
$highest3=0;
for ($i=1; $i<=7; $i++) {
if ($highest3<=${"reg$i"} && ${"reg$i"}!=$highest1 && ${"reg$i"}!=$highest2) {
$highest3 = ${"reg$i"};
}
}
#if any $reg.. are the same this chain will stop at the first met requirement for if. So if there are two areas with the same number only one will be shown!
if ($highest1 == $reg1) {
$area1= "Fractions, %, decim";
} elseif ($highest1 == $reg2) {
$area1= "Factors";
} elseif ($highest1 == $reg3) {
$area1= "Simplifying";
} elseif ($highest1 == $reg4) {
$area1= "Fractions of numbers";
} elseif ($highest1 == $reg5) {
$area1= "Share in ratio";
} elseif ($highest1 == $reg6) {
$area1= "Reverse Ratio";
} elseif ($highest1 == $reg7) {
$area1= "Compound interest";
} elseif ($highest1 == $reg8) {
$area1= "Problem Solving";
} else {
$area1= "Something went wrong";
}
if ($highest2 == $reg1) {
$area2= "Fractions, %, decim";
} elseif ($highest2 == $reg2) {
$area2= "Factors";
} elseif ($highest2 == $reg3) {
$area2= "Simplifying";
} elseif ($highest2 == $reg4) {
$area2= "Fractions of numbers";
} elseif ($highest2 == $reg5) {
$area2= "Share in ratio";
} elseif ($highest2 == $reg6) {
$area2= "Reverse Ratio";
} elseif ($highest2 == $reg7) {
$area2= "Compound interest";
} elseif ($highest2 == $reg8) {
$area2= "Problem Solving";
} else {
$area2= "Something went wrong";
}
if ($highest3 == $reg1) {
$area3= "Fractions, %, decim";
} elseif ($highest3 == $reg2) {
$area3= "Factors";
} elseif ($highest3 == $reg3) {
$area3= "Simplifying";
} elseif ($highest3 == $reg4) {
$area3= "Fractions of numbers";
} elseif ($highest3 == $reg5) {
$area3= "Share in ratio";
} elseif ($highest3 == $reg6) {
$area3= "Reverse Ratio";
} elseif ($highest3 == $reg7) {
$area3= "Compound interest";
} elseif ($highest3 == $reg8) {
$area3= "Problem Solving";
} else {
$area3= "Something went wrong";
}
Echo "<h3>The areas for development for this class are as follows:</h3><h2>".$area1."<br>".$area2."<br>".$area3."</h2>";
Are the values integers? If so simply assign them to an array, sort it and pick the last three values from it.
You might want to give example of what these values are and what you want to happen when #3 matches #4 (display both? display the first one?)
Sorry for the late reply...but just in case. There are many ways to do what you want but the way I would do it is as follows:
<?php
# assuming the scores are a string - however you get the values we just need them in an array
$scores = "97,37,55,82,99,97,55,97,73,100,62,91";
# explode the string into an array
$scores_array = explode(",", $scores);
# this makes:
// Array
// (
// [0] => 97
// [1] => 37
// [2] => 55
// [3] => 82
// [4] => 99
// [5] => 97
// [6] => 55
// [7] => 97
// [8] => 73
// [9] => 100
// [10] => 62
// [11] => 91
// )
# now put them in a new array - so that we can sort and count them
$sorted_array = array();
foreach ($scores_array as $key => $value) {
# a ternary for counting how many of each score we have
$sorted_array[$value] = (isset($sorted_array[$value]) ? $sorted_array[$value] + 1 : 1);
# this makes:
// Array
// (
// [37] => 1
// [55] => 2
// [62] => 1
// [73] => 1
// [82] => 1
// [91] => 1
// [97] => 3
// [99] => 1
// [100] => 1
// )
}
# sort the array by key (score)
ksort($sorted_array);
# get the top 3 in the array
$top_three_array = array_slice($sorted_array, -3, 3, true);
# output them
foreach ($top_three_array as $key => $value) {
echo $key . ": " . $value . "<br />";
}
# prints:
// 97: 3
// 99: 1
// 100: 1
?>

PHP: Check if a value of an array is a key of another array

I have this arrays:
$required_fields:
Array
(
[0] => email
)
$posted_fields:
Array
(
[name] => Roberto
[email] =>
[richiesta] => richiesta
)
I need to check if a value of $required_fields is in $posted_fields (and if it's null/empty).
Pseudocode:
foreach ($required_fields as $value_r)
{
foreach ($posted_fields as $key_p=>$value_p)
{
if (in_array($value_r,$posted_fields)
{
if ($value_p=='' || $value_p == NULL)
{
// others stuff
}
}
}
}
Why don't you something simplier, like
foreach ($required_fields as $required_value)
{
if(!isset($posted_fields[$required_value]) || trim($posted_fields[$required_value]) == "")
{
//Mandatory field not set or empty
}
}
In the code that you had provided I would change if (in_array($value_r,$posted_fields) line
foreach ($required_fields as $value_r)
{
foreach ($posted_fields as $key_p => $value_p)
{
if ($value_r == $key_p)
{
if ($value_p=='' || $value_p == NULL)
{
// others stuff
}
}
}
}
Use array_key_exists()
foreach ($required_fields as $value_r) {
if(array_key_exists($value_r, $posted_fields)) {
// value exists in key
}
}

How to send "null" or empty value to database through 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.

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;
}
}

Shorthand to check value in array

Is there a short way of doing this?
if ((isset($a['key']) && ($a['key'] == 'value')) {
echo 'equal';
// more code
}
else {
echo 'not equal';
// more code
}
I need to test lots of values on an array that can or cannot exist. I feel that this method is too verbose.
I could remove the isset() and mute the notices... but then I feel dirty.
Edit:
Answering Jack's question: "Could you give an example how you would test lots of values in an array?"
example:
if (isset($_GET['action']) && $_GET['action'] == 'view') {
//code
}
if (isset($_GET['filter']) && $_GET['filter'] == 'name') {
//code
}
if (isset($_GET['sort']) && $_GET['sort'] == 'up') {
//code
}
if (isset($_GET['tag']) && $_GET['tag'] == 'sometag') {
//code
}
etc...
For anyone still stumbling upon this question...
You could use PHP's coalescing operator:
if (($a['key'] ?? '') === 'value') {
echo 'equal';
// more code
}
else {
echo 'not equal';
// more code
}
See this question: using PHP's null coalescing operator on an array
I don't like to answer my own questions but I feel that the best and cleaner way to do this kind of checkings is to write a "helper funcion" like:
function iskeyval(&$a, $k, $v) {
return isset($a['key']) && ($a['key'] == 'value');
}
and then:
if (iskeyval($a, 'key', 'value')) {
...
}
else {
...
}
I have added comments to explain the code. Here is the code :
//this array maps the function with the get parameters
$functions = array (
"action" => "do_actions" ,
"filter" => "do_filters"
);
foreach ($_GET as $key=>$value) {
//check if this field is corresponding functions or not
if ( array_key_exists($key , $functions) ) {
call_user_func($functions[$key] , $key,$value);
}
}
function do_actions ($key , $value) {
//place your code here to play with this value
echo 'do_actions is called with ' . $key . 'and' . $value . "</br>";
}
function do_filters ($key , $value) {
//place your code here to play with this value
echo 'do_filters is called with ' . $key . ' and ' . $value . "</br>";
}
?>
$list = array(
0 => 'one',
1 => 'two',
2 => 'one',
3 => 'three',
4 => 'one',
);
if( #$list['xxx'] !== 'three')
echo 'Not ';
echo 'Equal';
Suppress the error reporting.

Categories