Could you write this 'cleaner' ? Just a simple question from a beginner:)
if(isset($_GET['tid']) && trim($_GET['tid'])!==""){
$act = 'tid';
$tid = trim($_GET['tid']);
}elseif(isset($_GET['fid']) && trim($_GET['fid'])!==""){
$act = 'fid';
$fid = trim($_GET['fid']);
}elseif(isset($_GET['mid']) && trim($_GET['mid'])!==""){
$act = 'mid';
}elseif(isset($_GET['act']) && trim($_GET['act'])!==""){
$act = trim($_GET['act']);
}else{
$act = "";
}
I would do it like this:
$tid = isset( $_GET['tid'] ) ? trim( $_GET['tid'] ) : '';
$fid = isset( $_GET['fid'] ) ? trim( $_GET['fid'] ) : '';
$mid = isset( $_GET['mid'] ) ? trim( $_GET['mid'] ) : '';
$act = isset( $_GET['act'] ) ? trim( $_GET['act'] ) : '';
if ( empty( $act ) ) // act not set, construct the act from the other GET vars
{
if ( !empty( $tid ) )
$act = 'tid';
else if ( !empty( $fid ) )
$act = 'fid';
else if ( !empty( $mid ) )
$act = 'mid';
}
edit: Of course you could make this even shorter, but the question was how it could be written to “improve its clarity”. And I understand clarity as something that makes it more easy to understand, what happens in a part of code. And I think the actual logic behind the original code gets quite clear with my solution.
I see nothing bad in your code apart from lack of indentation:
if(isset($_GET['tid']) && trim($_GET['tid'])!==""){
$act = 'tid';
$tid = trim($_GET['tid']);
}elseif(isset($_GET['fid']) && trim($_GET['fid'])!==""){
$act = 'fid';
$fid = trim($_GET['fid']);
}elseif(isset($_GET['mid']) && trim($_GET['mid'])!==""){
$act = 'mid';
}elseif(isset($_GET['act']) && trim($_GET['act'])!==""){
$act = trim($_GET['act']);
}else{
$act = "";
}
Although perhaps you could benefit from a function like this
function get_non_empty($field){
return isset($_GET[$field]) && trim($_GET[$field])!='' ? $_GET[$field] : NULL;
}
Definitely not the 'cleanest' solution, but a lot shorter:
$act = '';
foreach(array('tid', 'fid', 'mid', 'act') as $a) {
if(isset($_GET[$a]) && strlen(trim($_GET[$a])) > 0) {
$$a = trim($_GET[$act = $a]);
break;
}
}
This is nearly identical logically to what poke did (+1 for poke for beating me to it), but since we're talking about clarity I thought I'd show my take on it. I like to use FALSE instead of empty strings when it means something isn't being used. It feels like a more explicit way of saying "no". Also, I rarely use the non-bracketed version of if/else but for really short assignment statements I find it way easier to read.
$tid = isset($_GET['tid']) ? trim($_GET['tid']) : FALSE;
$fid = isset($_GET['fid']) ? trim($_GET['fid']) : FALSE;
$mid = isset($_GET['mid']) ? trim($_GET['mid']) : FALSE;
$act = isset($_GET['act']) ? trim($_GET['act']) : FALSE;
if ($act){ // act not set, construct the act from the other GET vars
if ($tid) $act = 'tid';
else if ($fid) $act = 'fid';
else if ($mid) $act = 'mid';
}
Careful with those raw GET values. You should clean those values up before processing them to make sure you are getting exactly what you want, especially if this is about to insert values to a database.
Here is one way. I would however probably do something differently with the tid,fid,mid stuff if I knew what they was intended for.
list($act,$val) = firstValidGETIn('tid','fid','mid','act');
switch($act) {
case 'act': $act = $val; break;
case null : $act = ""; break;
default : $$act = $val;
}
function firstValidGETIn()
{
foreach(func_get_args() as $key)
{
if(array_key_exists($key,$_GET) && trim($_GET[$key]))
return array($key, trim($_GET[$key]));
}
return array(null,null);
}
Related
I'm looking for a more elegant or efficient way to handle this if-statements. I'm kinda new to PHP and while the script below works, it looks kinda strange to me and I'm pretty sure there is a better way (performance and/or structure wise) to handle a case like this.
I have an array $atts and there can be two values in it:
border-top and border-bottom
These come from two checkboxes you can select, so there are 4 combinations. Either one, both, or none.
My code:
// First check
$border = '';
if ( ! empty( $atts['border']['border-top'] ) ) {
$border_top = $atts['border']['border-top'];
}
if ( ! empty( $atts['border']['border-bottom'] ) ) {
$border_bottom = $atts['border']['border-bottom'];
}
// Create the class
if ( ! empty( $border_top) ) {
if ( ! empty( $border_bottom) ) {
$border = 'border-top-and-bottom';
} else {
$border = 'border-top';
}
} else {
$border = 'border-bottom';
}
// Add class to the main array
if ( ! empty( $border ) ) { $attributes['class']['border'] = $border; }
Why I did it like this:
First check: The first two if-statements are there to check if they are set at all, since these are no booleans. If I don't select a checkbox there is no 0 value but instead doesn't create a value in $atts. Without the first two if-statements I would receive an PHP error.
Create the class: Here I try to see what combination was set. Either top and bottom, just one of those two or none. Especially this part of the code can be put in a better more elegant way, I think.
Add the class: Here I add the result of the part before as a new entry to the final array, or not if none of the checkboxes was selected.
I mean, so far it seems to work like it was intended.. I'm just curious if there is a better and shorter way to solve this case then all these if-statements.
edit:
Ok, looking at it outside the editor I noticed that was pretty dumb, since the first and middle part were kinda doing the same thing. I already narrowed it down:
$border = '';
if ( ! empty( $atts['border']['border-top'] ) ) {
if ( ! empty( $atts['border']['border-bottom'] ) ) {
$border = 'border-top-and-bottom';
} else {
$border = 'border-top';
}
} elseif ( ! empty( $atts['border']['border-bottom'] ) ) {
$border = 'border-bottom';
}
if ( ! empty( $border ) ) { $attributes['class']['border'] = $border; }
You can use the PHP's ternary operator :
This line will reduce your variable name in program :
$array = $atts['border'];
After will test the value of border-top, this line means :
"If $array['border-top'] is not empty, $top value will be 'border-top', else $top value will be null "
$top = (!empty($array['border-top'])) ? 'border-top' : '';
The same line for the border-bottom value :
$bottom = (!empty($array['border-bottom'])) ? 'border-bottom' : '';
Then we mix the var, this line means :
"If $top and $bottom are not empty, $border value will be $top + '-and-bottom', else, $border value will be $top + $bottom (One is empty)"
$border = (!empty($top) && !empty($bottom)) ? $top.'-and-bottom' : $top.$bottom;
Then we just set the var :
$attributes['class']['border'] = (!empty($border)) ? $border : '';
echo $attributes['class']['border'];
Final :
$array = $atts['border'];
$top = (!empty($array['border-top'])) ? 'border-top' : '';
$bottom = (!empty($array['border-bottom'])) ? 'border-bottom' : '';
$border = (!empty($top) && !empty($bottom)) ? $top.'-and-bottom' : $top.$bottom;
$attributes['class']['border'] = (!empty($border)) ? $border : '';
echo $attributes['class']['border'];
i have a tabe with many fields and i want to change one or many fields with the same update method , the problem is when i try to update it affect the others fields that i have not updated too .
this is my sql function :
<?php
if ($_REQUEST['fct']=="ModelUpdate")
{
if ( isset( $_REQUEST['day'] ) && isset( $_REQUEST['month'] ) && isset( $_REQUEST['year'] ) ) {
$D_DATE_NAISSANCE = "".$_REQUEST['year']."/".$_REQUEST['month']."/".$_REQUEST['day']."";
}else{
$D_DATE_NAISSANCE = $_REQUEST['model_bidthday'];
}
$PK_MODEL = isset($_REQUEST['PK_MODEL']) ? $_REQUEST['PK_MODEL'] : $_SESSION['PK_MODEL'];
$K_KEY_MODEL = isset($_REQUEST['K_KEY_MODEL']) ? $_REQUEST['K_KEY_MODEL'] : $_SESSION['K_KEY_MODEL'];
$FK_STUDIO = $_REQUEST['model_studio'];
//$S_LOGIN = $_REQUEST['model_username'];
//$S_EMAIL = $_REQUEST['model_adressmail'];
//$S_PASSWORD = $_REQUEST['S_PASSWORD'];
$S_FIRSTNAME = $_REQUEST['model_firstname'];
$S_LASTNAME = $_REQUEST['model_lastname'];
//$D_DATE_NAISSANCE = $_REQUEST['model_bidthday'];
$S_GENRE = $_REQUEST['model_gender'];
$S_COUNTRY_CODE = $_REQUEST['model_coutryCode'];
$S_CITY = $_REQUEST['model_city'];
$S_ZIP = $_REQUEST['model_zipcode'];
$S_ADRESS = $_REQUEST['adress'];
$S_NATIONALITY = $_REQUEST['model_nationality'];
$S_ETHNIE = $_REQUEST['model_ethnie'];
$S_CARD_ID_FRONT = $_REQUEST['S_CARD_ID_FRONT'];
$S_CARD_ID_BACK = $_REQUEST['S_CARD_ID_BACK'];
$S_IMAGE_CAM = $_POST['S_IMAGE_CAM'];
$sql = $sqlserver->prepare("UPDATE t_model SET FK_STUDIO=? , S_FIRSTNAME=? , S_LASTNAME=? , D_DATE_NAISSANCE=?, S_GENRE=? ,S_COUNTRY_CODE=?, S_CITY=? , S_ZIP=? , S_ADRESS=? , S_NATIONALITY=? , S_ETHNIE=? , S_CARD_ID_FRONT=?, S_CARD_ID_BACK=? , S_IMAGE_CAM=? where PK_MODEL=? and K_KEY_MODEL=?");
$r = $sql->execute(array($FK_STUDIO,$S_FIRSTNAME,$S_LASTNAME,$D_DATE_NAISSANCE,$S_GENRE,$S_COUNTRY_CODE,$S_CITY,$S_ZIP,$S_ADRESS, $S_NATIONALITY, $S_ETHNIE, $S_CARD_ID_FRONT, $S_CARD_ID_BACK,$S_IMAGE_CAM, $PK_MODEL,$K_KEY_MODEL)) or die(print_r($sql->errorInfo()));
$sql->closeCursor();
echo 1;
}
?>
In case you're using an sql server (as the name of the variable suggests) you can use ISNULL(expr1,expr2). In case the parameter in the query is null (expr1) then use the current value of that row (expr2).
// using php7's Null coalescing operator
// for php < 7 use: isset($_REQUEST['key']) ? $_REQUEST['key'] : replacement
$PK_MODEL = $_REQUEST['PK_MODEL'] ?? $_SESSION['PK_MODEL'];
$K_KEY_MODEL = $_REQUEST['K_KEY_MODEL'] ?? $_SESSION['K_KEY_MODEL'];
$FK_STUDIO = $_REQUEST['model_studio'] ?? NULL;
$S_FIRSTNAME = $_REQUEST['model_firstname'] ?? NULL;
$S_LASTNAME = $_REQUEST['model_lastname'] ?? NULL;
$S_GENRE = $_REQUEST['model_gender'] ?? NULL;
$S_COUNTRY_CODE = $_REQUEST['model_coutryCode'] ?? NULL;
$S_CITY = $_REQUEST['model_city'] ?? NULL;
$S_ZIP = $_REQUEST['model_zipcode'] ?? NULL;
$S_ADRESS = $_REQUEST['adress'] ?? NULL;
$S_NATIONALITY = $_REQUEST['model_nationality'] ?? NULL;
$S_ETHNIE = $_REQUEST['model_ethnie'] ?? NULL;
$S_CARD_ID_FRONT = $_REQUEST['S_CARD_ID_FRONT'] ?? NULL;
$S_CARD_ID_BACK = $_REQUEST['S_CARD_ID_BACK'] ?? NULL;
$S_IMAGE_CAM = $_POST['S_IMAGE_CAM'] ?? NULL;
$sql = $sqlserver->prepare("
UPDATE
t_model
SET
FK_STUDIO=IsNull(?,FK_STUDIO),
S_FIRSTNAME=IsNull(?,S_FIRSTNAME),
S_LASTNAME=IsNull(?,S_LASTNAME),
D_DATE_NAISSANCE=IsNull(?,D_DATE_NAISSANCE),
S_GENRE=IsNull(?,S_GENRE),
S_COUNTRY_CODE=IsNull(?,S_COUNTRY_CODE),
S_CITY=IsNull(?,S_CITY),
S_ZIP=IsNull(?,S_ZIP),
S_ADRESS=IsNull(?,S_ADRESS),
S_NATIONALITY=IsNull(?,S_NATIONALITY),
S_ETHNIE=IsNull(?,S_ETHNIE),
S_CARD_ID_FRONT=IsNull(?,S_CARD_ID_FRONT),
S_CARD_ID_BACK=IsNull(?,S_CARD_ID_BACK),
S_IMAGE_CAM=IsNull(?,S_IMAGE_CAM)
WHERE
PK_MODEL=?
AND K_KEY_MODEL=?
");
In case you're using MySQL, the same can be done via IFNULL.
Either way it's cruical that the server really gets a NULL-value (not only an empty string but NULL).
You could try to use dynamically created queries.
You'll have to have the input fields' names the same as your columns in the table that you're going to update.
Then pass all the variables to the superglobal $_POST this way you won't update anything that is empty.
In your update function loop through $_POST like this:
$sql = 'UPDATE t_model SET ';
foreach($_POST as $key=>$value){
if($value !== '' && !empty($value)) //checking if you don't have an empty value and you can add more exceptions here by doing '&& $key !== 'exception' or '&& $value !== "exception"'
$sql .= $key.' = :'.$key.', ';
}
$sql = rtrim($sql, ",")." where PK_MODEL=:PK_MODEL and K_KEY_MODEL=:K_KEY_MODEL ";
$query = $sqlserver->prepare($sql);
foreach($_POST as $key=>$value){
if($value !== '' && !empty($value)){
$query->bindValue(':'.$key, $value);
}
}
$query->execute();
$query->closeCursor();
echo 1;
This should work, I've been using the same structure for my dynamic admin panel and it works like a charm.
NOTE: I've changed some variable names to make it a little bit easier to read for potential other users
IMPORTANT EDIT: As suggested by #SZenC this could be vulnerable to SQL injection. This would be by adding input fields manually in the source code of the form.
This can all be prevented by adding an additional check in the loops like this:
$allowed_cols = array('col1', 'col2', 'col3');
if($value !== '' && !empty($value) && in_array($key, $allowed_cols)){
So the fix for this potential SQL injection is to edit the checks in the for loops
In php/wordpress I have made a function. I want to pass some parameteres inside the function so that it will show result according to that. So far now my function code is like this
$user_id = get_current_user_id();
function check_user_access($role, $action = NULL ) {
if( $role == 'subscriber') {
if( $action = 'check_customer' ) {
$check_customer = $wpdb->get_var("SELECT COUNT(id) FROM `table1` WHERE `user_id` = $user_id");
return $check_customer;
}
if( $action = 'check_users' ) {
$check_users = $wpdb->get_var("SELECT COUNT(id) FROM `table2` WHERE `user_id` = $user_id");
return $check_users;
}
}
}
Now I am using this function like this
$role = 'subscriber';
$check_customers = check_user_access($role, $action = 'check_users' );
if( $check_users <=1 ) {
//do something;
}
if( $check_users > 1 ) {
//do something other;
}
But its showing the result of $action = 'check_customer'. Means its working for the first block condition. Can someone tell me how to solve this? Am I doing something wrong?
change your
if( $action = 'check_customer' ) {}
to
if( $action == 'check_customer' ) {}
= means Assignment Operator
== means Comparison Operator
refer - from here
Right now I am using this code to grab a variable in my URL:
<?php
$transaction_id = $_GET['transaction_id'];
if($transaction_id == "") {
$transaction_id = 'NA';
}
?>
So far I have only been grabbing that single variable, but now I need to grab a total of 5 variables. Will everything still work properly and operate fast and smoothly if I just copy and paste multiple codes right next to each other like this:
<?php
$transaction_id = $_GET['transaction_id'];
if($transaction_id == "") {
$transaction_id = 'NA';
}
?>
<?php
$transaction_id2 = $_GET['transaction_id2'];
if($transaction_id2 == "") {
$transaction_id2 = 'NA';
}
?>
<?php
$transaction_id3 = $_GET['transaction_id3'];
if($transaction_id3 == "") {
$transaction_id3 = 'NA';
}
?>
Or is there a more efficient way to combine them all into one code?
Thanks for the help.
Make use of isset() construct
<?php
if(!isset($_GET['transaction_id'])) {
$transaction_id = 'NA';
}
if(!isset($_GET['transaction_id2'])) {
$transaction_id2 = 'NA';
}
if(!isset($_GET['transaction_id3'])) {
$transaction_id3 = 'NA';
}
?>
justo to be sure them all are setted and not empty
$na = 'NA';
$transaction_id = (isset($_GET['transaction_id']) && $_GET['transaction_id'] != '') ? $_GET['transaction_id'] : $na ;
$transaction_id2 = (isset($_GET['transaction_id2']) && $_GET['transaction_id2'] != '') ? $_GET['transaction_id2'] : $na ;
...
you could do a for loop
<?php
$transaction_id = array();
for($i=1;$i<6:$i++){
if( $_GET['transaction_id'.$i] == "") {
$transaction_id[] = 'NA'
}else{
$transaction_id[] = $_GET['transaction_id'.$i]
}
}
?>
This will make an array of transaction ids or NA
[0] => NA
[1] => 12345
[2] => 67890
[3] => 23454
[4] => NA
[5] => 55422
I don't know if this is better practice or not, maybe its just a different way.
Hope it helps.
P.S.
you will have to change your first $_GET['transaction_id']; to $_GET['transaction_id1'];
What I'm doing is, if I haven't got an ID in either $_POST or $_SESSION then redirecting. Preference is given to $_POST. So I have this:
$bool = 0;
if (isset($_POST['id'])) {
$bool = 1;
} elseif (isset($_SESSION['id'])) {
$bool = 1;
}
if (!$bool) {
...//redirect
}
Is there a quicker way to write this, APART from just removing the braces?
if(!( isset($_POST['id']) || isset($_SESSION['id']) ))
redirect();
(not sure if I understand how what's given to $_POST is preference).
You could just do:
$has_id = isset($_POST['id']) || isset($_SESSION['id']);
if (!$has_id) {
// redirect
}
(I'd recommend you to give your variables more descriptive names than just $bool.)
Although if you aren't using the variable for anything else, you could just do:
if (!isset($_POST['id']) && !isset($_SESSION['id'])) {
// redirect
}
if (isset($_POST['id']) || isset($_SESSION['id'])) {
$bool = 1;
}
This will do it, simples
$bool = (isset($_POST['id']) || isset($_SESSION['id'])) ? 1 : 0; // if isset, 1
($bool == 1?header(Location: www.whatever.com):null;
Using Conditional Operator, you can achieve this in one line statement
Example:
c = (a == b) ? d : e;