9

現在、次の構造を使用して、複数のパラメーターを mysqli クエリにバインドすることに対処する必要があります。

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....

以下のコードを使用して疑問符の数を計算し、それをクエリに挿入します。

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

私の質問は、動的に必要なだけ多くの入力をクエリに処理する方法が必要です。ハードコーディングは、bind_param()これを処理するための本当に悪い方法のようです。

PHPバージョン5.4.10を使用しています

4

1 に答える 1

23

残念ながら、デフォルトでは bind_param() は個別の変数の代わりに配列を受け入れません。しかし、PHP 5.6 以降では、このトリックを行う素晴らしい改善があります。

任意の数の変数を mysqli クエリにバインドするには、引数 unpacking operatorが必要です。操作を可能な限りシンプルかつスムーズにします。

たとえば、mysql のIN()演算子で PHP 配列を使用するには、次のコードが必要です。

// our array
$array = ['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   
于 2013-07-26T06:29:47.260 に答える