mysql bind_param_如何在PHP中动态绑定mysqli bind_param参数?

佴普松
2023-12-01

我一直在学习为我的sql查询使用准备和绑定的语句,我已经出来了这个到目前为止,它的工作正常,但它是不是动态的,当涉及到多个参数或没有任何参数需要时,

public function get_result($sql,$parameter)

{

# create a prepared statement

$stmt = $this->mysqli->prepare($sql);

# bind parameters for markers

# but this is not dynamic enough...

$stmt->bind_param("s", $parameter);

# execute query

$stmt->execute();

# these lines of code below return one dimentional array, similar to mysqli::fetch_assoc()

$meta = $stmt->result_metadata();

while ($field = $meta->fetch_field()) {

$var = $field->name;

$$var = null;

$parameters[$field->name] = &$$var;

}

call_user_func_array(array($stmt, 'bind_result'), $parameters);

while($stmt->fetch())

{

return $parameters;

//print_r($parameters);

}

# close statement

$stmt->close();

}

这就是我如何调用对象类,

$mysqli = new database(DB_HOST,DB_USER,DB_PASS,DB_NAME);

$output = new search($mysqli);

有时我不需要传递任何参数,

$sql = "

SELECT *

FROM root_contacts_cfm

";

print_r($output->get_result($sql));

有时我只需要一个参数,

$sql = "

SELECT *

FROM root_contacts_cfm

WHERE root_contacts_cfm.cnt_id = ?

ORDER BY cnt_id DESC

";

print_r($output->get_result($sql,'1'));

有时我只需要一个以上的参数,

$sql = "

SELECT *

FROM root_contacts_cfm

WHERE root_contacts_cfm.cnt_id = ?

AND root_contacts_cfm.cnt_firstname = ?

ORDER BY cnt_id DESC

";

print_r($output->get_result($sql,'1','Tk'));

所以我相信这一行对于上面的动态任务来说并不足够,

$stmt->bind_param("s", $parameter);

要动态构建一个bind_param,我已经在其他帖子上发现了这一点.

call_user_func_array(array(&$stmt, 'bind_params'), $array_of_params);

而我试图修改一些代码从php.net,但我无处不在,

if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+

{

$refs = array();

foreach($arr as $key => $value)

$array_of_param[$key] = &$arr[$key];

call_user_func_array(array(&$stmt, 'bind_params'), $array_of_params);

}

为什么??有什么想法我可以使它工作吗?

或者也许有更好的解决方案?

谢谢.

 类似资料: