0

I have list of parameters and their values. I want to build mysql update string based on whether values are present or not. One way to check using if condition like below

if (!empty($value['p_status']) || !empty($value['quantity'])){
      $strSet = '';
      if (!empty($value['p_status'])) {
             $strSet .= "status='$value[p_status]',";
       }
      if (!empty($value['quantity'])) {
            $strSet .= "amount='$value[quantity]',";
      }
      if (!empty($value['shipping_freight'])) {
          $strSet .= "shipping_freight='$value[shipping_freight]',";
      }
   }
   $strSet = trim($strSet,',');
   db_query("update table1 set ".$strSet." where pr1=123");

But there can be lots of parameters. Is there is any better way to do it ?

1
  • loop it like foreach($value as $key =>$value) then if (!empty($key)) Commented Jul 4, 2015 at 6:21

2 Answers 2

2

To avoid writing so many if conditions, simply use a loop.

foreach($values as $key=>$value)
{
    if(!empty($value))
        str = str." $key = '$value',";
}
$str=trim($str,',');
Sign up to request clarification or add additional context in comments.

Comments

0

if your $value array can use the same keys as the MySQL field names that would be much simpler!
e.g. if $value['p_status'] could simply be $value['status'] and $value['quantity'] could be $value['amount'] then you could do something like this:

$strSet = '';
foreach ($value as $field_name=>$field_value) {
  if (!empty($strSet)) $strSet .= ',';
  if (!empty($field_value)) $strSet .= "{$field_name}='{$field_value}'";
}
db_query("update table1 set ".$strSet." where pr1=123");

Oh, and remember:
In PHP the empty() function will return true for NULL, an empty string and zero - so if the quantity/amount is zero your sql won't update the field!
Also, you should really escape the values you are updating to prevent sql injection.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.