gpt4 book ai didi

php - Mysql XAMPP 不要将负值插入行中

转载 作者:行者123 更新时间:2023-11-29 11:00:46 26 4
gpt4 key购买 nike

如何告诉数据库不接受、插入或更新来自 php 计算的负值。

考虑这个 php 代码:

<?php include('index2.php'); ?>
<?php include('db.php'); ?>
<?php
$mobile = $_SESSION['mobile'];
$date = date('M-d,Y H:i:s');
$date2 = date('M-d,Y');

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$amount = $_POST['amount'];
$balance = $_POST['balance'];

$balancenow = $balance - $amount;

if ($amount > $balance) {
$sql3 = "UPDATE users SET balance = '$balancenow'
WHERE mobile = '$mobile'";

if ($conn->query($sql3) === TRUE) {
echo '<a href="index2.php"></a>';
} else {
echo "0";
}
} else {
echo '<script language="javascript">';
echo 'alert("You don't have enough coupon balance")';
echo '</script>';
echo '<a href="index2.php"></a>';
}
$conn->close();
?>

现在考虑上面的例子:“金额”为 500,余额为 250,这反过来给我们计算:

$balancenow = $balance - $amount;

= 250-500 = -250

现在在这种情况下,如何告诉数据库不接受负值并给出 else 语句..

感谢任何帮助..

最佳答案

好吧,我认为从数据库端验证是正确的选择,它迫使程序员以正确的方式编写代码。

将列架构更新为 UNSIGNED INT 以仅存储非负值

Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

您还可以验证来自 PHP 的数据,但它是第二级。

关于php - Mysql XAMPP 不要将负值插入行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42313345/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com