在客户端收集一篇文章的变量后,这里是将它们放入 mysql 数据库的 php 代码。
它有效,但有没有更短的方法,无需重复所有项目 - 五次
:
- 一次在 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
中字段的顺序应与传入参数的顺序相同。
关于php - 将数据存储到数据库的更短方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56919984/