Dynamic SQL Concatenation with PHP MySQLi Prepared Statements

时间:2019-04-17 02:37:17

标签: php mysql mysqli prepared-statement

I am writing a PHP prepared statement using MySQLi prepared statements where the first bound parameter is a user's ID and the second parameter can be one of 5 different pieces of SQL code (the $redeemLimitCheckRange variable) based on other conditions represented as a string. I am having trouble binding the second parameter.

I have tried binding the SQL code as a string, have tried using the SQL CONCAT() function, but neither seem to work.

<?php
    if($dbRedeemStart != '' && $dbRedeemEnd != ''){
        $redeemLimitCheckRange = "AND DATE(chg_date) >='$dbRedeemStart' AND DATE(chg_date) <= '$dbRedeemEnd'";
    else if($dbRedeemStart != '' && $dbRedeemEnd == ''){                                                                                                                      
        $redeemLimitCheckRange = "AND DATE(chg_date) >= '$dbRedeemStart'";
    else if($dbRedeemStart == '' && $dbRedeemEnd != ''){
        $redeemLimitCheckRange = "AND DATE(chg_date) <= '$dbRedeemEnd'";
    }else{
        $redeemLimitCheckRange = "";
    }

    $sql = "SELECT COUNT(recId) totalRedeem FROM transactions WHERE userId = ? AND `type` = 'Redeemed' ?";
    $stmt = mysqli_stmt_init($connection);

    if(!mysqli_stmt_prepare($stmt, $sql)){
        error_log("mysqli_stmt_prepare failure", 0);
    }else{
        mysqli_stmt_bind_param($stmt, "is", $usrId, $redeemLimitCheckRange);
        mysqli_stmt_execute($stmt);
        $rslt = mysqli_stmt_get_result($stmt);
        mysqli_stmt_close($stmt);
    }
?>

Currently, php is failing on the mysqli_stmt_prepare($stmt, $sql) line and throwing an error.

0 个答案:

没有答案