Подготовленные заявления с различными параметрами - PullRequest
0 голосов
/ 13 мая 2018

Все, что мне нужно, это знать, как получить mysqli_stmt_bind_param, который может принимать 1-4 строки. С заполнителями ("?") В mysqli_stmt_bind_param будут работать только "$ stmt," s ", $ Interest" при поиске 1 интереса или "$ stmt," ssss ", $ Interest" при поиске "Любого интереса" для.

Спасибо!

    $Interest = $_GET['interestId'];

$sql = "SELECT * from User WHERE (Interest1 = '$Interest' OR Interest2 = '$Interest' OR Interest3 = '$Interest') OR '$Interest' = 'Any Interest';";


        echo "<h1 class='contact-intro'>";
        echo " Welcome to the business card library for $Interest! </h1>";

$stmt = mysqli_stmt_init($link);
//Prepare the prepare statements
if (!mysqli_stmt_prepare($stmt, $sql)) {
    echo "SQL statement failed";

} else {
    //Bind parameters to the placeholder(s)
    mysqli_stmt_bind_param($stmt, $Interest);
    //Run parameters inside database
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    //   $result = mysqli_query($link, $sql);
      $resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
(lots of echos.......)

ОБНОВЛЕННЫЙ ПОЛНЫЙ КОД И ОПИСАНИЕ ВЫПУСКА.

Ответы [ 2 ]

0 голосов
/ 13 мая 2018

Вы можете поместить значения для ваших заполнителей в переменную массива. А в mysqli_stmt_bind_param () вы можете использовать оператор splat ... - как в приведенном ниже коде, чтобы вы могли обрабатывать различное количество заполнителей и его значений для одного поля таблицы.

Вы можете сделать что-то вроде этого:

$interest_array = array('basketball', 'basketball', 'basketball', 'basketball');
$s_marks = str_repeat("s", count($interest_array)); 
mysqli_stmt_bind_param($stmt, $s_marks, ...$interest_array);

Это:

mysqli_stmt_bind_param($stmt, $s_marks, ...$interest_array);

Будет рассматриваться как:

mysqli_stmt_bind_param($stmt, "ssss", $interest1,$interest2,$interest13, $interest4);

Ваш обновленный код (еще не проверен):

$Interest = $_GET['interestId'];
$sql = "SELECT * from User WHERE (Interest1 = ? OR Interest2 = ? OR Interest3 = ?) OR ? = 'Any Interest';";
$placeholder_count  = substr_count($sql, '?');
$s_marks = str_repeat("s", $placeholder_count); // creates sss string
$interest_array = array_fill(0, $placeholder_count, $Interest); // creates an array of the same values.

echo "<h1 class='contact-intro'>";
echo " Welcome to the business card library for $Interest! </h1>";

 $stmt = mysqli_stmt_init($link);

 if (!mysqli_stmt_prepare($stmt, $sql)) {
    echo "SQL statement failed";
} else {
    mysqli_stmt_bind_param($stmt, $s_marks, ...$interest_array);
    mysqli_stmt_execute($stmt);
}

Остальная часть кода будет применяться в зависимости только от количества заполнителя в строке sql.

0 голосов
/ 13 мая 2018

Почему бы не сделать это так?

// prepare and bind
$stmt = $conn->prepare("SELECT * from User WHERE (Interest1 = ? OR Interest2 = ? OR Interest3 = ?) OR ? = 'Any Interest';");
$stmt->bind_param("sss", $Interest, $Interest, $Interest);

if ($stmt->execute()){
    echo "<h1 class='contact-intro'>";
    echo " Welcome to the business card library for $Interest! </h1>";
}else{
    echo "SQL statement failed";
}
$stmt->close();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...