繁体   English   中英

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

[英]How to Update and Delete MySQL Table in PHP using this kind of method?

使用 laracasts 'The 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 中将表名和数组作为参数传递?

我想这就是你要找的:

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) {
        //
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM