具有动态WHERE子句的预备语句 [英] Prepared Statements with dynamic WHERE clause

查看:44
本文介绍了具有动态WHERE子句的预备语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我的问题是我有一个函数,但是我想在执行查询时解析它的不同WHERE子句.例如:

OK so my question is I have a function but i want to parse it different WHERE clauses for when it executes a query. for example:

function query($where)
{
$query = $mysql->prepare("SELECT * FROM table WHERE ?");
$query->bind_param("s", $where);
$query->execute();

...

}

query("table.id=123 AND table.name='abc'");

我了解到这是不正确的,所以我应该如何执行类似的操作,在很多地方我需要在不同的WHERE子句中使用此函数,并且为每个函数创建函数是不切实际的,因此不能创建函数,并且直接调用它.

I have learnt that this is incorrect So how do I perform something similar, i have many places where I need to use this function with different WHERE clauses, and make a function for each is impractical and so is not making a function and calling it directly.

推荐答案

对于带有WHERE子句的已准备好的语句,您必须指定稍后要指定的值,例如:

For a prepared statement with a WHERE clause you have to specify what values will be specified later, for instance:

SELECT * FROM table WHERE ID=?

如果要使其更具动态性,可以在一个函数中指定查询,然后调用查询函数.例如,您有以下内容:

if you want to make it more dynamic you can have specify the query in one function and then call the query function. For example, you have this:

function query($query, $param, $where)
{
$query = $mysql->prepare($query);
$query->bind_param($param, $where);
$query->execute();

...

} 

在其他功能中,您说:

$results=query("SELECT * FROM table WHERE Id=?","s","1");

通过使查询类可以包含where子句数组,可以使此操作更加复杂:

you could make this even more sophisticated by making a query class that can contain an array of where clauses:

class query
{
  public $query;
  public $param;
  public $where;
}

$query=new query();
$query->query="SELECT * FROM Table WHERE group=? AND name like ?";
$query->param="ss";
$query->where = array();
$query->where[]="administrators";
$query->where[]="sam";

,然后将查询功能更改为:

and change your query function to look like:

function SQLCall(query $query)
{
$db = $mysql->prepare($query->query);
call_user_func_array(array(&$db, 'bind_param'), $where)
$db->execute();

...

}

这篇关于具有动态WHERE子句的预备语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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