是否有为MySQL插入绑定名为PDO参数的快捷方式? [英] Is there a shortcut for binding named PDO params for MySQL inserts?

查看:44
本文介绍了是否有为MySQL插入绑定名为PDO参数的快捷方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要使用命名参数,PDO似乎需要大量重复.我一直在寻找一种使用列/数据对的单个实例简化它的方法,而不必多次重新键入列名甚至变量名.

PDO seems to require a lot of repetition if you want to use named parameters. I was looking for a way to make it simpler, using a single instance of column/data pairs -- without having to re-type column names or even variable names multiple times.

我自己回答这个问题,是因为我编写了一个函数,该函数相当优雅,基本上,我想炫耀它(并帮助希望这样做的人).

I'm answering this question myself because I wrote a function that I think does this pretty elegantly, and basically, I wanted to show it off (and help people looking to do the same).

我不确定我是否是第一个想到这个的人,或者是否有我没有预料到的问题.如果您有更好的东西,请随时告诉我,或提供您自己的解决方案.

I'm not at all sure if I'm the first one to think of this, or if there are any issues I didn't foresee. Feel free to let me know, or supply your own solution, if you have something better.

推荐答案

从@equazcion的答案开始,但是使用略有不同的代码方法:

Starting from @equazcion's answer, but using slightly different code method:

function bindFields($fields) {
    return implode(",", array_map(function ($f) { return "`$f`=:$f"; },
        array_keys($fields)));
}

或者如果您希望使用传统的INSERT语法而不是特定于MySQL的INSERT...SET语法:

Or if you want traditional INSERT syntax instead of the MySQL-specific INSERT...SET syntax:

function bindFields($fields) {
    return "(" . implode(",", array_map(function ($f) { return "`$f`"; },
        array_keys($fields))) . ")"
    . " VALUES (" . implode(",", array_map(function ($f) { return ":$f"; },
        array_keys($fields))) . ")";
}

这篇关于是否有为MySQL插入绑定名为PDO参数的快捷方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆