如何使用这种方法在PHP中更新和删除MySQL表?

时间:2018-09-05 02:21:54

标签: php mysql sql laravel

使用laracasts“ PHP Practitioner”课程,我了解到可以使用以下格式插入表中:

public function insert($table, $parameters)
{
    $sql = sprintf(
        'insert into %s (%s) values (%s)',
        $table,
        implode(', ', array_keys($parameters)),
        ':' . implode(', :', array_keys($parameters))
    );

    try {
        $statement = $this->pdo->prepare($sql);

        $statement->execute($parameters);
    } catch (\Exception $e) {
        //
    }
}

我如何仅使用表名和数组作为PHP中的参数来使用此方法更新和删除数据?

1 个答案:

答案 0 :(得分:0)

我认为这是您想要的:

public function delete($table, $where = [])
{
    $_where = array_reduce(array_keys($where), function($prev,$key){
        return $prev . ' AND ' . $key . '=:' . $key;
    },'1=1');
    $sql = sprintf(
        'delete from %s where %s',
        $table,
        $_where
    );

    try {
        $statement = $this->pdo->prepare($sql);

        $statement->execute($where);
    } catch (\Exception $e) {
        //
    }
}


public function update($table, $values, $where=[]){
    $_where = array_reduce(array_keys($where), function($prev, $key){
        return sprintf("%s AND %s=:%s", $prev, $key, $key);
    },'1=1');
    $_set = array_reduce(array_keys($values), function($prev, $key){
        return sprintf("%s,%s=:%s", $prev, $key, $key);
    }, '');
    $sql = sprintf(
        'update %s set %s where %s',
        $table,
        $_set,
        $_where
    );
    try {
        $statement = $this->pdo->prepare($sql);

        $statement->execute($where);
    } catch (\Exception $e) {
        //
    }
}