在$ bind_param()中动态绑定参数; Mysqli的 [英] Dynamically bind params in $bind_param(); Mysqli
问题描述
我有处理所有查询的数据库类,将对数据库进行查询 我有mysqli准备工作正常. bind_param也可以正常工作,但是问题是我想动态定义变量类型. 这是我的代码
I have DB class which is dealing all queries will be made to database I have mysqli prepare working fine. bind_param is also working fine but the problem is I want to define variable type dynamically. here is my code
public function query($sql, $params = array()){
$this->_error = false;
if($this->_query = $this->_mysqli->prepare($sql)){
$x = 1;
if(count($params)){
foreach($params as $param){
$this->_query->bind_param($x, $param);
$x++;
}
}
IN PDO的拳头参数定义了位置,所以我猜每次设置X = 1和x ++时,此函数就可以正常运行,
但在bind_param
中,第一个参数定义了类型,我猜
如php.net手册所说
所以如果用户按下我设置的整数值有什么办法
x =我
对于字符串
设
对于所有4种类型,依此类推...
IN PDO fist parameter defines position I guess so this function runs fine by setting X = 1 and x++ everytime,
but in bind_param
first argument defines type I guess
as php.net manual says
so is there is any way if user pushes integral value I set
x = i
for string
x = s
so on and so forth for all 4 types ...
喜欢
if((int)$param->){
x = i;
}
有想法的人吗?
预先感谢
推荐答案
下面是一个可以帮助您的示例(prepare()
函数是一个类方法).
Here is an example that could help ( prepare()
function is a class method ).
function prepare( $query, $bind = array() )
{
if ( !$stmt = $this->mysqli->prepare( $query ) )
throw new Exception( 'Query failed: ' . $query . PHP_EOL . $this->mysqli->error );
// if $bind is not an empty array shift the type element off the beginning and call stmt->bind_param() with variables to bind passed as reference
if ( $type = array_shift( $bind ) )
call_user_func_array(
array( $stmt, 'bind_param' ),
array_merge( array( $type ), array_map( function( &$item ) { return $item; }, $bind ) )
);
if ( !$stmt->execute() )
throw new Exception( 'Execute failed: ' . PHP_EOL . $stmt->error );
// choose what to return here ( 'affected_rows', 'insert_id', 'mysqli_result', 'stmt', 'array' )
}
用法示例:
$db->prepare( "SELECT * FROM user WHERE user_name = ? OR user_email = ?", [ 'ss', $user_name, $user_name ] );
这篇关于在$ bind_param()中动态绑定参数; Mysqli的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!