mysqli从db中提取十进制值

时间:2017-01-23 18:29:54

标签: php mysql mysqli

我正在尝试从我的数据库中提取小数,但是当我尝试将其设为int并且我不知道如何修复它因为我很愚蠢而我甚至不配叫程序员。有人可以帮忙吗?

if (isset($_POST['Add'])) {

$Date = $_POST['Date'];
$Amount = $_POST['Amount'];
$LegalFees = 0.00;
$CheckID = $_POST['Check_ID'];

$DateAdded = date("Y/m/d", strtotime($_POST['Date']));

$result = mysqli_query($conn, "SELECT CheckID FROM checks WHERE CheckID='" . $CheckID . "'");
$CurrentPayment = mysqli_query($conn, "SELECT payments FROM checks WHERE CheckID='" . $CheckID . "'");

$TotalPayment = $Amount + $CurrentPayment;

if (mysqli_num_rows($result) > 0) {

    $sqlinsert = $conn->query("INSERT INTO payments (Date,Amount,LegalFees,CheckID)Values('{$DateAdded}','{$Amount}','{$LegalFees}','{$CheckID}')");
    $sqlupdate = $conn->query("UPDATE checks SET payments=" . $TotalPayment . " WHERE checkID=" . $CheckID . "");
} else {
    $_SESSION["CheckIDFail"] = "Yes";
}

}

所以基本上它应该在数据库中选择一个十进制的付款并将其存储到$ CurrentPayment中,但它不能,因为它试图使小数为int。

其余代码我没有遇到任何问题,它可以正常工作。只需要知道如何正确地拉小数。我认为它与fetch或其他什么有关?我不知道,有人请帮助这个可怜的人吗?

1 个答案:

答案 0 :(得分:1)

我认为问题是尝试将结果集(数组)转换为数字。 PHP不关心您的数字是小数还是整数。

$Date = $_POST['Date'];
$Amount = $_POST['Amount'];
$LegalFees = 0.00;
$CheckID = $_POST['Check_ID'];
$DateAdded = date("Y/m/d", strtotime($_POST['Date']));

$result = mysqli_query($conn, 
                       "SELECT payments FROM checks WHERE CheckID='" . $CheckID . "'") 
          or die(mysqli_error($conn));  


$currentPayment = 0;

if (mysqli_num_rows($result) > 0){
    // Get the "row" from the "result set". 
    // While loop is only added to illustrate the method of iterating through the results
    // If you only expect one row in the output, this should still work fine
    while($row = mysqli_fetch_assoc($result)){
        $currentPayment += $row['payments'];
    }

    $TotalPayment = $Amount + $currentPayment;


    mysqli_query($conn, "INSERT INTO payments (Date,Amount,LegalFees,CheckID)
                     values('{$DateAdded}','{$Amount}','{$LegalFees}','{$CheckID}')")
                     or die(mysqli_error($conn));

    mysqli_query($conn, "UPDATE checks SET 
                     payments=" . $TotalPayment . " WHERE checkID=" . $CheckID . "") 
                     or die(mysqli_error($conn));
} 
else {
     // No rows returned
     $_SESSION["CheckIDFail"] = "Yes";
}


有几件事:

  • 保持程序内查询类型(实际上甚至在应用程序内)的一致性。尽量不要在程序性(mysqli_query())和面向对象($conn->query)方法之间来回切换。

  • 使用准备好的查询来防止查询中SQL注入的威胁 - How to create a secure mysql prepared statement in php?

  • 偶尔绊倒是可以的:)