使用准备好的语句PHP

时间:2018-10-20 07:02:51

标签: php mysqli prepared-statement

这是我用来从表wp_formdata中获取当月数据的代码

HTML:

<div class="result" id="result" name="result">

            <?php echo $head1; ?> <?php echo $out; ?> <?php echo $head2; ?> 
</div>

PHP:

if ($_POST['result_options'] == 'Current_Month') {   

    $now = new \DateTime('now');
    $CurrMonth = $now->format('m');
    $CurrYear = $now->format('Y');

    $sql ="Select date,select_bank,entry_type,income_cat,expense_cat,amount,expense_cat_sub from wp_formdata WHERE MONTH(?) = MONTH(CURRENT_DATE()) AND YEAR(?) = YEAR(CURRENT_DATE()) order by date ";

    $stmt = mysqli_stmt_init($conn);
    if(!mysqli_stmt_prepare($stmt,$sql)) {
        $message =  '<h1 style="color:red;padding-top:5%;">SQL Error !!</h1>';

    } else {
        mysqli_stmt_bind_param($stmt,"ss", $CurrMonth, $CurrYear);
        mysqli_stmt_execute($stmt);
        $result= mysqli_stmt_get_result($stmt);
        $out = "";

        while($row = mysqli_fetch_assoc($result)) {
            $out .= "<tr><td>".$row["date"]."</td><td>".$row["select_bank"]."</td><td>".$row["entry_type"]."</td><td>".$row["income_cat"]."</td><td>".$row["expense_cat"]."</td><td>".$row["expense_cat_sub"]."</td><td>".$row["amount"]."</td></tr>";
        }
    }
}

我已验证数据库连接,它可以按预期工作。我还验证了变量$CurrMonth$CurrYear的值:

echo $CurrMonth; //will give output 10 

echo $CurrYear;  //will give output 2018

但是我没有任何搜索结果。有任何解决建议吗?

2 个答案:

答案 0 :(得分:2)

SQL中的月份和年份比较看起来不正确,您正在将当前月份(并从中MONTH(?)中提取月份)与当前日期的月份(MONTH(CURRENT_DATE()))进行比较。您无需使用任何参数就可以摆脱困境,因为您需要将记录(MONTH(date))中的日期月份与当前月份(与年份相同)进行比较(我假设)。

$sql ="Select date,select_bank,entry_type,income_cat,expense_cat,
                 amount,expense_cat_sub 
          from wp_formdata 
          WHERE MONTH(date) = MONTH(CURRENT_DATE()) 
                   AND YEAR(date) = YEAR(CURRENT_DATE()) 
          order by date ";

始终值得在PHPMyAdmin之类的地方检出SQL,以确保在使用PHP运行之前可以得到结果。

万一需要在其他月份使用,可以使用参数,但不要从中提取月份...

$sql ="Select date,select_bank,entry_type,income_cat,expense_cat,
                 amount,expense_cat_sub 
          from wp_formdata 
          WHERE MONTH(date) = ?
                   AND YEAR(date) = ?
          order by date ";

答案 1 :(得分:0)

您正在将PHP当前日期与DB当前日期进行比较。

在您的SQL字符串中,应将MONTH(?)YEAR(?)替换为MONTH(date)YEAR(date)。 此时,您应该删除mysqli_stmt_bind_param($stmt,"ss", $CurrMonth, $CurrYear);,因为SQL字符串没有参数。