php - 将数据存储到数据库的更短方法

标签 php mysql

在客户端收集一篇文章的变量后,这里是将它们放入 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/

相关文章:

php - JPEG压缩PHP图片到内存

php - Laravel - 更好的错误跟踪

php:将谷歌地图网址放入数据库中

php - CodeIgniter - is_unique 表单验证规则无法正常工作

php - 获取 JSON 格式的 Moodle 数据

php - 替换数组值以增加

php - 为什么这个 PHP 表单不起作用?

mysql - Node.js MySQL 模型设计

php - 具有未知数据库的家园的 Laravel 5

PHP IF ELSE - 如果似乎被忽略了?