具有参数的PHP函数可更新MySQL表中的所有列,但不需要所有参数,也不总是更新所有列

时间:2019-03-21 12:09:44

标签: php mysql

我有一个带有列的MySQL表:

opID, opDateAdded, opLastUpdated, opUser, opPropertySaleID, opArray, refurbID, opRefurbCost, opViewingArranged, opOfferAccepted, opOfferAcceptedID, opPaon, opStreet, opPostcode, opPropertyType, opViewingDate, opViewingBy, opViewingPersonName, opFloorArea, opBedrooms, opBathrooms, opReceptions, opAskingPrice, opValuation, opOptMatchingBedrooms, opOptMatchingBuild, opOptMatchingType, opOptSimilarFloor, opOptDistance, opLatitude, opLongitude, opNotes

我希望有一个功能可以更新此表的列,但有时仅需要更新3-4列,而并非总是全部。

我只是想知道解决这个问题的最佳方法是什么?

我可以创建一个像这样的函数

function updateOpportunity($opID, $opDateAdded, $opLastUpdated, $opUser, $opPropertySaleID, $opArray, $refurbID, $opRefurbCost, $opViewingArranged, $opOfferAccepted, $opOfferAcceptedID, $opPaon, $opStreet, $opPostcode, $opPropertyType, $opViewingDate, $opViewingBy, $opViewingPersonName, $opFloorArea, $opBedrooms, $opBathrooms, $opReceptions, $opAskingPrice, $opValuation, $opOptMatchingBedrooms, $opOptMatchingBuild, $opOptMatchingType, $opOptSimilarFloor, $opOptDistance, $opLatitude, $opLongitude, $opNotes) {
   //update
}

并将它们设置为可选,然后检查是否已设置它们,然后再更新这些行(在MySQL中使用IFNULL)

或者创建一个属性类并传递一个属性可能更好,更整洁:

function updateOpportunity($property) {
   //update
}

我只是想知道是否有一个标准来创建一个函数来更新大列,而这些列并不总是需要同时更新。

2 个答案:

答案 0 :(得分:1)

您可以创建一个适用于所有表和列的通用函数。

function update($table, $data, $id)
{

    $set= array();
    foreach ($data as $key => $value)
    {
        $set[] = "{$key} ='".mysqli_real_escape_string($value)."'";

    }

    $sql = "UPDATE {$table} SET ".implode(', ', $set)." WHERE ID = '$id'";
    mysqli_query($connection,$sql);

}

这是使用准备好的语句的函数。

function update($table, $data, $id)
    {

         $setPart = array();
         $bindings = array();

         foreach ($data as $key => $value)
         {
            $setPart[] = "{$key} = :{$key}";
            $bindings[":{$key}"] = $value;
         }

          $bindings[":id"] = $id;

          $sql = "UPDATE {$table} SET ".implode(', ', $setPart)." WHERE ID = :id";
          $stmt = $pdo->prepare($sql);
          $stmt->execute($bindings);

    }

这里,$ connection是一个mysqli_connection对象,我们需要创建该对象以执行任何查询以了解此click here

第二个函数$ pdo是PDO连接对象,我们需要创建该对象来执行查询click here以获得更多信息。

您可以阅读link以获取更多信息。

为防止SQL注入,您可以使用mysqli_real_escape_string()函数  click here以获得更多信息。

答案 1 :(得分:1)

您可以在上课时这样做。

class Table {
    private $pdo;
    private $table;
    private $where;
    private $key;
    private $id;
    private $values;
    private $sql;

    public function __construct($pdo, $table = null, $key = null, $where = array(), $id = null) {
        $this->pdo = $pdo;
        $this->table($table);
        $this->values($values);
        $this->key($key);
        $this->id = $id;
    }

    public function table($table) {
        $this->table = $table;
        return $this;
    }

    public function where($where) {
        $this->where = $where;
        $this->id    = null;
        return $this;
    }

    public function key($key) {
        $this->key   = $key;
        return $this;
    }

    public function id($id) {
        $this->id = $id;
        $this->where = array();
        return $this;
    }

    private function resetValues() {
        $this->values = array();
        return $this;
    }

    private function getWhere() {
         $where  = '';
         $comma  = ' WHERE ';
         foreach ($this->where as $key => $value) {
            $where  .= $comma . $key . '=?';
            $values[] = $value;
            $comma = ',';
         }
         if ($this->id) {
             if (!$this->key) {
                 throw new \Exception('primary key required but not specified');
             }
             $where  .= $comma . $key . '=?';
             $values[] = $value;
             $comma = ',';
         }
         return $where;
    }

    private function getWhat(&$values) {
         $fields = '';
         $comma  = '';

         foreach ($values as $key => $value) {
            $fields  .= $comma . $key . '=?';
            $values[] = $value;
            $comma = ',';
         }
         return $fields;
    }

    public function update(array $values) {
         $this->sql  = "UPDATE {$this->table} SET ";
               . $this->resetValues()->getWhat()
               . $this->getWhere();
         return $this;
    }

    public function perform() {
         // Check $this->sql exists ecc.
         return $this->pdo->prepare($this->sql)->execute($this->values());
    }
}

那么你可以做:

$TUsers = new Table($pdo);
$TUsers->table('users')->key('user_id');

...
$TUsers->update(['name' => 'Leonardo'])->id(137)->perform();

请注意,类用户不知道该类正在使用哪个DB接口-您可以通过抽象化连接接口(此处为构造函数提供的$ pdo)和实际执行(此处{{1 }}。

如果需要,您可能希望通过将实际SQL的MD5(不包含列值)与LRU保存的语句数组进行比较来缓存准备好的语句(不过,我相信PDO可能已经这样做了)。如果该语句不在高速缓存中,则您可以对其进行prepare(),否则可以从高速缓存中取回该语句:

perform()

可以使用INSERT,DELETE,SELECT等方法或诸如ORDER,GROUP等辅助功能来扩展同一类。 并且它可以对其数据进行一致性检查和/或UTF-8清理您的字段和/或记录每个符合某些规范的查询,依此类推。

您还可以查看DoctrinePropel