本文介紹了使用一個具有可變數量的輸入變量的 bind_param()的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我嘗試像這樣使用變量綁定:
I try to use variable binding like this:
$stmt = $mysqli->prepare("UPDATE mytable SET myvar1=?, myvar2=... WHERE id = ?")) {
$stmt->bind_param("ss...", $_POST['myvar1'], $_POST['myvar2']...);
但有些 $_POST['...'] 可能是空的,所以我不想在數據庫中更新它們.
but some of the $_POST['...'] might be empty so I don't want to update them in the DB.
考慮空 $_POST['...'] 的所有不同組合是不切實際的,雖然我可以根據我的需要構建字符串UPDATE mytable SET...",但 bind_param() 是不同的野獸.
It's not practical to take into account all the different combination of empty $_POST['...'] and although I can build the string " UPDATE mytable SET..." to my needs, bind_param() is a different beast.
我可以嘗試將其調用構建為字符串并在其上使用 eval() 但感覺不對:(
I could try building its call as a string and use eval() on it but it doesn't feel right :(
推薦答案
您可以使用 call_user_func_array
函數調用帶有可變編號或參數的 bind_param
方法:
$paramNames = array('myvar1', 'myvar2', /* ... */);
$params = array();
foreach ($paramNames as $name) {
if (isset($_POST[$name]) && $_POST[$name] != '') {
$params[$name] = $_POST[$name];
}
}
if (count($params)) {
$query = 'UPDATE mytable SET ';
foreach ($params as $name => $val) {
$query .= $name.'=?,';
}
$query = substr($query, 0, -1);
$query .= 'WHERE id = ?';
$stmt = $mysqli->prepare($query);
$params = array_merge(array(str_repeat('s', count($params))), array_values($params));
call_user_func_array(array(&$stmt, 'bind_param'), $params);
}
這篇關于使用一個具有可變數量的輸入變量的 bind_param()的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!