Bind multiple parameters into mysqli query

China☆狼群 提交于 2019-11-25 22:47:42

问题


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

if ($words_total == 1)
{
    $statement -> bind_param(\"s\", $words[0]);
}
else if ($words_total == 2)
{
    $statement -> bind_param(\"ss\", $words[0], $words[1]);
}
else if ($words_total == 3)
{
    $statement -> bind_param(\"sss\", $words[0], $words[1], $words[2]);
}

//and so on....

I work out the number of question marks using the code below and insert it into my query:

$marks = \"\";
for($i = 1; $i<=$words_total; $i++) {
    if ($i == $words_total)
    {
        $marks .= \"?\";
    }
    else
    {
        $marks .= \"?,\";
    }
}

My question is surely there must be a way of handling as many inputs into the query as I need dynamically. Hardcoding the bind_param() seems like a really bad way of handling this.

I am using php version 5.4.10


回答1:


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   


来源:https://stackoverflow.com/questions/17870999/bind-multiple-parameters-into-mysqli-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!