如何制作 PDO 类方法,用于在 arg 中使用未知数量的参数插入/更新/删除
问题描述
目前我正在尝试创建一个 PDO 类,我将在其中使用一种方法来运行诸如 INSERT、UPDATE 或 DELETE 之类的查询.
Currently Im trying to create a PDO class where I will have a method to run a query like INSERT, UPDATE, or DELETE.
例如,这是我的 SELECT 方法
For examaple this is my method for a SELECT
我只是这样称呼它:
到目前为止,我知道 runQuery 应该像这样工作:
And so far I know that a runQuery should work something similar to this:
不使用方法插入示例:
但我想把它变成一个通用的方法,我可以简单地传递sql语句,就像这样:
But I want to make it into an universal method where i simply can pass the sql sentence, something like this:
但查询可能恰好是
$query = "插入角色 (idRol, NomRol) VALUES ('4','test')";
$query = "INSERT INTO roles (idRol, NomRol) VALUES ('4','test')";
或
$query = "插入电影 (movName, movLength, movArg) VALUES ('name1','15','movie about...')";
$query = "INSERT INTO movies (movName, movLength, movArg) VALUES ('name1','15','movie about...')";
那么我如何对 arg $query 进行切片,以便我可以获取所有正在使用的变量以创建一个通用的 runQuery?
So how do I slice the arg $query so I can get all the variables that are being used in order to make an universal runQuery?
因为我可以想象我的方法应该是这样的
Because I can imagine that my method should be something like this
推荐答案
您需要向函数中添加第二个参数.只是一个数组,所有这些变量都会在其中.根据定义,数组可以包含任意数量的元素,这正好可以解决您的问题:
You need to add a second parameter to your function. Simply an array where all those variables would go. An array by definition can have an arbitrary number of elements, which solves your problem exactly:
这个简单的函数将运行任何查询.您可以在我专门介绍 PDO 辅助函数的文章中查看使用示例:
this simple function will run ANY query. You can see the usage example in my article dedicated to PDO helper functions:
如您所见,现在您的函数可以用于具有任意数量参数的任何查询
As you can see, now your function can be used with any query with any number of parameters
这篇关于如何制作 PDO 类方法,用于在 arg 中使用未知数量的参数插入/更新/删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!