php - 将数据放在数据库中的更短方法
问题描述
在客户端为一篇文章收集变量后,这里是将它们放在 mysql 数据库中的 php 代码。
它可以工作,但是否有更短的方法,无需重复所有项目 - five times
:
- 一次btn_save
声明
- 两次sql
声明
- 两次st
执行
function btn_save($img, $up, $branch, $title, $sub, $intro, $story, $down, $linked, $tags, $status){
global $db;
$sql = "insert into arts (img, up, branch, title, sub, intro, story, down, linked, tags, status) values (:aimg, :aup, :abranch, :atitle, :asub, :aintro, :astory, :adown, :alinked, :atags, :astatus)";
$st = $db->prepare($sql);
$st->execute([
":aimg" => $img,
":aup" => $up,
":abranch" => $branch,
":atitle" => $title,
":asub" => $sub,
":aintro" => $intro,
":astory" => $story,
":adown" => $down,
":alinked" => $linked,
":atags" => $tags,
":astatus" => $status
]);
}
解决方案
使用?
而不是命名占位符和func_get_args
函数,您可以将代码简化为:
function btn_save($img, $up, $branch, $title, $sub, $intro, $story, $down, $linked, $tags, $status){
global $db;
// values as array
$args = func_get_args();
// create a string `?, ?, ? ...` with count of `?` same as count of arguments
$placeholders = implode(',', array_fill(0, count($args), '?'));
$sql = "insert into arts (img, up, branch, title, sub, intro, story, down, linked, tags, status) values ($placeholders)";
$st = $db->prepare($sql);
// as `$args` already array - just pass it as is
$st->execute($args);
}
唯一相关的条件?
是字段的顺序insert
应该与传入参数的顺序相同。
推荐阅读
- javascript - 在映射后合并并过滤两个对象
- excel - 使用 xlwings 启动特定版本的 Excel
- pytorch - PyTorch - 如何使用平均 2d 池化作为数据集转换?
- javascript - 数字的 Angular Typescript 接口在表单验证中设置为 null ,然后一元加运算符如果未设置则抛出错误
- command-line - 使用 ImageMagick 加快缩小大型 JPEG 图像的大小
- c - valgrind 仍然可达泄漏的示例
- postgresql - 注册/登录页面在 localhost 中工作,但在 Heroku 上出现应用程序错误 (h12/503)
- c++ - 为什么`iota(0) | take(0)` 不是 C++20 中的模型范围::sized_range?
- single-sign-on - 如何在单点登录 (SSO) 中处理令牌到期?
- android - 如何检查手机号码是否存在于同一用户的android设备中?