how to escape empty and/or black field on PDO update? - php

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

Related

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

Two " Array to string conversion" notices (Prestashop)

I'm not so sure whether it is smart to post both problems in one question, but lets try:
So, I was checking my server's error log and it still has two notices, both about "Array to string conversion in [...]".
The first line should be this:
$replace = $route['keywords'][$key]['prepend'].$params[$key].$route['keywords'][$key]['append'];
Context:
// Build an url which match a route
if ($this->use_routes || $force_routes) {
$url = $route['rule'];
$add_param = array();
foreach ($params as $key => $value) {
if (!isset($route['keywords'][$key])) {
if (!isset($this->default_routes[$route_id]['keywords'][$key])) {
$add_param[$key] = $value;
}
} else {
if ($params[$key]) {
$replace = $route['keywords'][$key]['prepend'].$params[$key].$route['keywords'][$key]['append'];
} else {
$replace = '';
}
$url = preg_replace('#\{([^{}]*:)?'.$key.'(:[^{}]*)?\}#', $replace, $url);
}
}
$url = preg_replace('#\{([^{}]*:)?[a-z0-9_]+?(:[^{}]*)?\}#', '', $url);
if (count($add_param)) {
$url .= '?'.http_build_query($add_param, '', '&');
}
}
The second one is this line:
$uri_path = __PS_BASE_URI__.$id_image.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
as part of this:
// legacy mode or default image
$theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_.$ids.($type ? '-'.$type : '').'-'.(int)Context::getContext()->shop->id_theme.'.jpg')) ? '-'.Context::getContext()->shop->id_theme : '');
if ((Configuration::get('PS_LEGACY_IMAGES')
&& (file_exists(_PS_PROD_IMG_DIR_.$ids.($type ? '-'.$type : '').$theme.'.jpg')))
|| ($not_default = strpos($ids, 'default') !== false)) {
if ($this->allow == 1 && !$not_default) {
$uri_path = __PS_BASE_URI__.$ids.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
} else {
$uri_path = _THEME_PROD_DIR_.$ids.($type ? '-'.$type : '').$theme.'.jpg';
}
} else {
// if ids if of the form id_product-id_image, we want to extract the id_image part
$split_ids = explode('-', $ids);
$id_image = (isset($split_ids[1]) ? $split_ids[1] : $split_ids[0]);
$theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_.Image::getImgFolderStatic($id_image).$id_image.($type ? '-'.$type : '').'-'.(int)Context::getContext()->shop->id_theme.'.jpg')) ? '-'.Context::getContext()->shop->id_theme : '');
if ($this->allow == 1) {
$uri_path = __PS_BASE_URI__.$id_image.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
} else {
$uri_path = _THEME_PROD_DIR_.Image::getImgFolderStatic($id_image).$id_image.($type ? '-'.$type : '').$theme.'.jpg';
}
}
return $this->protocol_content.Tools::getMediaServer($uri_path).$uri_path;
}
public function getMediaLink($filepath)
{
return $this->protocol_content.Tools::getMediaServer($filepath).$filepath;
}
PHP is not my strength, so I have no idea what to do :/
Also I found some other questions about Array to string notices, but it seemed to me like you can't solve them the same way...
Thanks in advance for any help!
This error is appearing because some of the variables in these two lines are supposed to be String but they are actually array.
You need to print all the variables used in these 2 lines using the var_dump() function of PHP, this will tell you which of the variables are actually an Array, but they are supposed to be a String as per your code.
On the basis of the output, you need to modify your code to fix the issue.

Validate a numeric value range from html form textbox. PHP or Javascript

I have a form that contains a number of textboxes i.e. Volome, Gain, Treble, Middle and Bass. Only whole numbers can be entered, which is validated with javascript and the Maxlength is set to, so no problem there. But how do I make sure that only numbers between 0 and 65535 are entered.
<?php
$name = $_POST['ampMod'];
$volume = 'Volume = '. $_POST['volume'];
$gain = 'Gain = '. $_POST['gain'];
$treble = 'Treble = '. $_POST['treble'];
$middle = 'Middle = '. $_POST['middle'];
$bass = 'Bass = '. $_POST['bass'];
if($volume != null && $gain != null && $treble != null && $middle != null && $bass != null)
{
echo "<h3> $name </h3>";
echo "<table><tr>";
echo "<td>$volume</td>";
echo "<td>$gain</td>";
echo "<td>$treble</td>";
echo "<td>$middle</td>";
echo "<td>$bass</td>";
}
else
{echo ("Please try again. Values must be between 0-65535. 0=Off 65535=Full On 10<br>Click here to try again!");}
?>
It is important to mention that your $volume, $gain, $treble, $middle and $bass will never actually be null as you have assigned a string to them in addition to the $_POST value. In addition you should always check if the $_POST values exist before trying to use them (or you will get an undefined notice message).
Here is an example for a PHP version based on the code you had (untested, but should work fine).
<?php
function isValidRange( $value, $low = 0, $high = 65535) {
// validate / cast value as int (add additional validation here
$value = (int)$value;
if ( $value > $high || $value < $low ) {
// return null (not a valid value)
return null;
}
// otherwise the value is valid so return it
return $value;
}
// make sure the $name var is safe to use
$name = ( isset($_POST['ampMod']) ) ? htmlentities($_POST['ampMod'],ENT_QUOTES,'UTF-8') : null;
$volume = ( isset($_POST['volume']) ) ? isValidRange($_POST['volume']) : null;
$gain = ( isset($_POST['gain']) ) ? isValidRange($_POST['gain']) : null;
$treble = ( isset($_POST['treble']) ) ? isValidRange($_POST['treble']) : null;
$middle = ( isset($_POST['middle']) ) ? isValidRange($_POST['middle']) : null;
$bass = ( isset($_POST['bass']) ) ? isValidRange($_POST['bass']) : null;
if( isset($volume) && isset($gain) && isset($treble) && isset($middle) && isset($bass) )
{
echo "<h3> $name </h3>";
echo "<table><tr>";
echo "<td>Volume = $volume</td>";
echo "<td>Gain = $gain</td>";
echo "<td>Treble = $treble</td>";
echo "<td>Middle = $middle</td>";
echo "<td>Bass = $bass</td>";
echo "</tr></table>";
} else {
echo ("Please try again. Values must be between 0-65535. 0=Off 65535=Full On 10<br>Click here to try again!");}
?>
Lastly I would not recommend just relying on JavaScript to actually check if your values are safe to use (i.e. echo them out), but using js as a pre-warning to users and then properly validating with PHP is the best way to go.
Just do something like this? Don't know why you would want to go between 0 and 65535. I doubt you want them to go that high. If you do just change 10 to 65535
if($value > 10 || $value < 0)
{
echo "Value cant be higher then 10 or lower then 0";
}
This makes sure the value is between 10 and 0
In situations like this, I often prefer to silently clean the form input. You've got client-side validation in place already. If the value is higher than allowed, just set the value to the maximum allowed instead of showing an error message.
// Clean the posted data and prevent notices if not set
$volume = (isset($_POST['volume'])) ? (int) $_POST['volume'] : 0;
// Make sure the value is within a certain range
$min = 0;
$max = 10;
$volume = min($max, max($min, $volume));
You can make use of the filter extension (bundled by default since 5.2):
$FILTER_VALIDATE_KNOB = array(
'filter' => FILTER_VALIDATE_INT,
'options' => array(
'min_range' => 0,
'max_range' => 65535,
)
);
$res = filter_input_array(INPUT_POST, array(
'ampMod' => $FILTER_VALIDATE_KNOB,
'volume' => $FILTER_VALIDATE_KNOB,
'gain' => $FILTER_VALIDATE_KNOB,
'treble' => $FILTER_VALIDATE_KNOB,
'middle' => $FILTER_VALIDATE_KNOB,
'bass' => $FILTER_VALIDATE_KNOB,
));
if (is_null($res) || in_array(null, $res, true)) {
// some or all fields are missing
// - missing fields have null value
} elseif (in_array(false, $res, true)) {
// some or all fields have a wrong value
// - wrong values have false value
}
I would do it with javascript. That way, you wouldn't have to submit the form and if the user types a higher number the alert (or something nicer) is shown:
In the input field, just call the javascript function:
<input id="thefirstnumbervalue" type="text" onchange="checknumber('thefirstnumbervalue')" />
<input id="thesecondnumbervalue" type="text" onchange="checknumber('thesecondnumbervalue')" />
In the function:
function checknumber(theid){
var mynumbervalue = document.getElementById(theid).value;
if (mynumbervalue > 65535){
document.getElementById(theid).value = "65535";
alert("Please try again. Values must be between 0-65535. ...");
}
if(mynumbervalue < 0){
document.getElementById(theid).value = "0";
alert("Please try again. Values must be between 0-65535 ...");
}
}
This is a simple approach in raw javascript. If you use ajax and jquery the result could be easier and nicer. This is complementary to the php solution, as you should also check the data before inserting in your database.

I need a more efficient way of checking if multiple $_POST parameters isset

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])){
...
}
}

How can I rewrite this code to improve its clarity?

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

Categories