首页 > 解决方案 > 将数据放在数据库中的更短方法

问题描述

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

标签: phpmysql

解决方案


使用?而不是命名占位符和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应该与传入参数的顺序相同。


推荐阅读