我有保存在表上的sql查询。
tbl_query
SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = '$getBadgeID'
然后在PHP代码上:
$query = mysqli_query($con, "SELECT * FROM tbl_query");
while($data = mysqli_fetch_array($query))
{
//SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = '$getBadgeID'
$getQuery = $data['sql_query'];
$qTotal = mysqli_query($con, $getQuery);
$dTotal = mysqli_fetch_array($qTotal);
echo $dTotal['TOTAL'];
}
当我尝试运行该代码时,它显示的结果总计为0。但是,如果我在查询数据中删除此WHERE badgeid_fk = '$getBadgeID'
,则结果不是0。
即使存在变量'$getBadgeID'
答案 0 :(得分:3)
PHP将此变量视为字符串,这就是为什么生成此查询的结果
SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = '$getBadgeID' // its not converting your variable with 150502
在这里您可以使用备用名称,也可以与定界符一起使用,例如:
您当前的查询是:
SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = '$getBadgeID'
通过以下方式更改查询:
SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = ':getBadgeID'
现在,您需要使用str_replace
将分隔符替换为变量,例如:
while($data = mysqli_fetch_array($query))
{
$getQuery = str_replace(":getBadgeID", $getBadgeID , $data['sql_query']);
}
为什么我在这里使用定界符,因为您的变量$ getBadgeID在php脚本中具有定义的值,并且不是动态的。
在我们的聊天对话中,@ executable建议使用准备好的语句的另一种解决方案。
编辑:
根据与@Bananaapple的讨论,我正在为将来的访问者添加此注释,Prepared Statement是另一种更安全的解决方案,如果要避免SQL注入,请选择Prepared语句。
答案 1 :(得分:3)
推荐的方法是使用prepared statements清理查询并保护您免受SQL注入。下面的漫画举例说明什么是SQL注入。
为回答这个问题,我们发现在您的查询中变量$getBadgeID
被读为文本而不是变量。我建议您使用此代码使用准备好的语句:
<?php
$conn = new mysqli("HOST", "USER", "SECRET", "DATABASE");
if($stmt = $conn->prepare("SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = ?")) {
$stmt->bind_param("s", $getBadgeID);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$total = $row['TOTAL'];
}
$stmt->close();
}
$conn->close();
var_dump($total);
如果您想进行更多调试:
<?php
if(isset($getBadgeID) and $getBadgeID != ""){
$conn = new mysqli("HOST", "USER", "SECRET", "DATABASE");
if($stmt = $conn->prepare("SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = ?")) {
$stmt->bind_param("s", $getBadgeID);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$total = $row['TOTAL'];
}
$stmt->close();
}else{
echo "Query is wrong";
}
$conn->close();
var_dump($total);
}else{
echo 'Variable $getBadgeID is empty';
}