Using laracasts 'The PHP Practitioner' course I learn that I can insert into table using following format:
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?
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) {
//
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.