PHP MySQL不更新包含小数

时间:2016-01-28 18:25:43

标签: php mysql sql-update

当我尝试使用PHP使用以下查询字符串更新表时:

UPDATE card_designs SET `card_price` = '6180', 
                        `annual` = '257.3', 
                        `initial_payment` = '6512.3' 
WHERE card_id = '1'

它无法正确更新。 card_price值正确放入。但是,年度为0initial_payment6255.00

字段是VARCHARDECIMAL还是DOUBLE并不重要。如果该值有一个小数,那么它就搞砸了。

此外,如果我在SQL客户端中运行上述查询,查询工作正常。

以下是构造查询的PHP代码。我正在使用mysqli:

$sql = "UPDATE ". $table ." SET ";
$updates = array();
foreach ($variables as $field => $value) {
    array_push($updates, "`$field` = '$value'");
}
$sql .= implode(', ', $updates);

//Add the $where clauses as needed
if (!empty($where)) {
    foreach ($where as $field => $value) {
        $value = $value;

        $clause[] = "$field = '$value'";
    }
    $sql .= ' WHERE '. implode(' AND ', $clause);   
}

if (!empty( $limit)) {
    $sql .= ' LIMIT '. $limit;
}

$query = $this->mysqli->query($sql);

1 个答案:

答案 0 :(得分:1)

我假设您的数据库表字段数据类型是十进制(9,2)

// Prepare query
$table = "card_designs";
$variables = array(
    "card_price" => "6180.00",
    "annual" => "257.3",
    "initial_payment" => "6512.3"
);    

$where = array(
    "id" => "1"
);

$sql = "UPDATE ". $table ." SET ";
$updates = array();
foreach ($variables as $field => $value) 
{
    array_push($updates, "$field = $value");
}

$sql .= implode(', ', $updates);
//Add the $where clauses as needed
if (!empty($where)) 
{
    foreach ($where as $field => $value) 
    {
        $value = $value;
        $clause[] = "$field = $value";
    }

    $sql .= ' WHERE '. implode(' AND ', $clause);   
}

if (!empty( $limit)) 
{
    $sql .= ' LIMIT '. $limit;
}

// Run query
if ($mysqli->query($sql))
{
    echo "Record updated successfully";
}