5

Use a bind_param () with a variable number of entries

 2 years ago
source link: https://www.codesd.com/item/use-a-bind-param-with-a-variable-number-of-entries.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Use a bind_param () with a variable number of entries

advertisements

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']...);

but some of the $_POST['...'] might be empty so I don't want to update them in the DB.

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.

I could try building its call as a string and use eval() on it but it doesn't feel right :(


You could use the call_user_func_array function to call the bind_param method with a variable number or arguments:

$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);
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK