[英]How to Update and Delete MySQL Table in PHP using this kind of method?
Using laracasts 'The PHP Practitioner' course I learn that I can insert into table using following format:使用 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) {
//
}
}
How I update and delete data using this method just passing table name and array as arguments in PHP?我如何使用这种方法更新和删除数据,只是在 PHP 中将表名和数组作为参数传递?
I think this is what you looking for:我想这就是你要找的:
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.