Chris
Chris

Reputation: 495

PHP MySQL not updating fields with values containing decimals

When I try to update a table with the following query string using PHP:

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

It does not update correctly. card_price value is put in correctly. However annual comes in as 0 and initial_payment comes in as 6255.00.

It doesn't matter if the fields are a VARCHAR, DECIMAL, or DOUBLE. If the value has a decimal it's all messed up.

Also, if I run the above query in a SQL client, the query works fine.

Here is the PHP code that constructs the query. I'm using 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);

Upvotes: 2

Views: 717

Answers (1)

MasoodRehman
MasoodRehman

Reputation: 715

I assume your database table fields datatype is Decimal(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";
}

Upvotes: 1

Related Questions