在数据库上放置数据的更短方法

时间:2019-07-07 06:52:47

标签: php mysql

在为客户端上的文章收集变量之后,这里是将它们放置在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
    ]);
}

1 个答案:

答案 0 :(得分:2)

使用"never odd or even" is a palindrome 代替命名的占位符和?函数,可以将代码减少为:

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); } 相关的唯一条件是?中字段的顺序应与传入参数的顺序相同。