lundi 7 décembre 2020

What is this if statement short hand in this mySQL statement?

I am using UserSpice with the Store module. To update a product it uses a base DB function called "update" (adequately named). I am unfamiliar with this if statement short hand, and I can't figure out how to rewrite this so that it takes the $fields array and implodes them correctly. //$table, $id, and $fields all are echoing out correctly both before and after the function, but the $sql statement is not.

public function update($table, $id, $fields){
        
    $sql   = "UPDATE {$table} SET " . (empty($fields) ? "" : "`") . implode("` = ? , `", array_keys($fields)) . (empty($fields) ? "" : "` = ? ");
            $is_ok = true;
    
            if (!is_array($id)) {
                $sql     .= "WHERE id = ?";
                $fields[] = $id;
            } else {
                if (empty($id))
                    return false;
    
                if ($where_text = $this->_calcWhere($id, $fields, "and", $is_ok))
                    $sql .= "WHERE $where_text";
            }
            echo $sql;
            if ($is_ok)
                if (!$this->query($sql, $fields)->error())
                    return true;
    
            return false;
        }

The $sql Statement is echoing out like this:

UPDATE store_inventory SET `item` = ? , `category` = ? , `shortDesc` = ? , `description` = ? , `flavor` = ? , `nutrients` = ? , `uses` = ? , `price` = ? , `qoh` = ? , `cost` = ? , `digital` = ? , `disabled` = ? , `active` = ? , `Featured` = ? , `url` = ? , `topcat` = ? WHERE id = 3

The syntax looks correct, but the ? mark is weird. That should be outputting the values of the keys from $fields.

So looking at the $sql Statement this is what I understand it to be saying:

  1. "UPDATE $table //(which is correct)
  2. SET" //(make the columns equal these values)
  3. . (empty($fields) ? "" : "`") //concat and- check if $fields is empty, if it is then return blank, else return the opening apostrophe
  4. . implode("` = ? , `", array_keys($fields)) //concat and-implode the $fields Array with closing apostrophe, the equals signifier for mysql, and a question mark for the 'value', comma for mySQL, and opening apostrophe for next key/value pair.
  5. . (empty($fields) ? "" : "` = ? "); //concat and- check if $fields is empty, if it is then return blank, else return the closing apostrophe then final equal signifier and a question mark for the final 'value' along with encasement and Statement semicolon.

So I think the question mark is supposed to be a shorthand if statement, but it's clearly not working. I did get the statement $sql .= "WHERE id = ?"; to work by replacing the question mark with {$id}.

So is the question mark supposed to be next to the colon? or is this just bad all together?

Aucun commentaire:

Enregistrer un commentaire