php mysqli 准备语句中的减法运算这是正确的方法吗?
Subtraction operation in php mysqli prepared statement is this the right way to do it?
对于 sql 查询中的准备语句,这种执行减法运算的方法是否正确?
$sql = "UPDATE users set credits = (credits-$price) WHERE username = ?";
根据$price的价值减去用户积分的代码
$price = $row0['price'];
$sql = "UPDATE users set credits = (credits-$price) WHERE username = ?;";
$stmt1 = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt1, $sql)) {
$db_err = array("error" => "Database");
echo json_encode($db_err);
} else {
mysqli_stmt_bind_param($stmt1, "s", $_SESSION['username']);
mysqli_stmt_execute($stmt1);
您需要为 $price
变量使用占位符才能正确使用准备好的语句。除非您能够将值与可能值列表进行比较,否则连接值 永远不会 安全。
$sql = "UPDATE users set credits = (credits - ?) WHERE username = ?;";
if(!mysqli_stmt_prepare($stmt1, $sql)) {
...
} else {
mysqli_stmt_bind_param($stmt1, "ss", $price, $_SESSION['username']);
mysqli_stmt_execute($stmt1);
}
请注意,many reasons 最好使用对象语法。以下是您的操作方法:
if($stmt1 = $mysqli->prepare("UPDATE users set credits = (credits - ?) WHERE username = ?")) {
$stmt1->bind_param("ss", $price, $_SESSION['username']);
$stmt1->execute();
} else {
//notice I use `$stmt1->error` to get the actual error
$db_err = array("error" => $stmt1->error);
echo json_encode($db_err);
}
对于 sql 查询中的准备语句,这种执行减法运算的方法是否正确?
$sql = "UPDATE users set credits = (credits-$price) WHERE username = ?";
根据$price的价值减去用户积分的代码
$price = $row0['price'];
$sql = "UPDATE users set credits = (credits-$price) WHERE username = ?;";
$stmt1 = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt1, $sql)) {
$db_err = array("error" => "Database");
echo json_encode($db_err);
} else {
mysqli_stmt_bind_param($stmt1, "s", $_SESSION['username']);
mysqli_stmt_execute($stmt1);
您需要为 $price
变量使用占位符才能正确使用准备好的语句。除非您能够将值与可能值列表进行比较,否则连接值 永远不会 安全。
$sql = "UPDATE users set credits = (credits - ?) WHERE username = ?;";
if(!mysqli_stmt_prepare($stmt1, $sql)) {
...
} else {
mysqli_stmt_bind_param($stmt1, "ss", $price, $_SESSION['username']);
mysqli_stmt_execute($stmt1);
}
请注意,many reasons 最好使用对象语法。以下是您的操作方法:
if($stmt1 = $mysqli->prepare("UPDATE users set credits = (credits - ?) WHERE username = ?")) {
$stmt1->bind_param("ss", $price, $_SESSION['username']);
$stmt1->execute();
} else {
//notice I use `$stmt1->error` to get the actual error
$db_err = array("error" => $stmt1->error);
echo json_encode($db_err);
}