Bind multiple parameters into mysqli query

后端 未结 1 1357
迷失自我
迷失自我 2020-11-22 04:53

Right now I need to use the following structure to cope with binding multiple parameters into a mysqli query:

if ($words_total == 1)
{
    $statement -> b         


        
1条回答
  •  清酒与你
    2020-11-22 05:28

    Unfortunately, by default, bind_param() doesn't accept an array instead of separate variables. However, since PHP 5.6 there is a magnificent improvement that will do the trick.

    To bind an arbitrary number of variables into mysqli query you will need an argument unpacking operator. It will make the operation as simple and smooth as possible.

    For example, to use a PHP array with a mysql's IN() operator, you will need the following code

    // our array
    $words = ['a','b','c']; 
    
    // create an SQL query with placeholders and prepare it
    $in    = str_repeat('?,', count($array) - 1) . '?'; //  returns ?,?,?...
    $sql   = "SELECT name FROM table WHERE city IN ($in)"; 
    $stmt  = $mysqli->prepare($sql);
    
    // create the types string dynamically and bind an array
    $types = str_repeat('s', count($array)); // returns sss...
    $stmt->bind_param($types, ...$array); 
    
    // execute and fetch the rows
    $stmt->execute();
    $result = $stmt->get_result(); // get the mysqli result
    $data = $result->fetch_all(MYSQLI_ASSOC); // fetch the data   
    

    0 讨论(0)
提交回复
热议问题