开发者

sprintf changing the number format

开发者 https://www.devze.com 2023-04-12 08:13 出处:网络
I\'m having a problem with sprintf(), using it to store a mysql query into a var to use it later. just to inform, I\'m using adodb library for database related operations.

I'm having a problem with sprintf(), using it to store a mysql query into a var to use it later.

just to inform, I'm using adodb library for database related operations.

being $value=25.5 and $id=5 for exampl开发者_如何学运维e, i have something like

$value = number_format($baseValue, 2, ".", "");

$query = sprintf("Insert into table_name (id, value) values (%d, $.02f)", $id, $value);
$db->Execute($query);

there's a condition before this that decides if there is another $query being made before this one. if that first query doesn't run this one runs ok being the query

Insert into table_name (id, value) values (5, 25.50)

but if the first query runs then i get an error on this one because the query turns out as

Insert into table_name (id, value) values (5, 25,50)

i tried to print $value just right before the sprintf() and it still has the right format, why on earth is this happening and how do i solve it?

Edit: $value isn't even used or changed until this moment


You are basically doing a equivalent number to string conversion twice, first with number_format() and then with printf() and the %f modifier. Replacing $.02f with %s should be enough.

The reason why printf() is not generating a valid English format number is because it's using the regional settings (see setlocale() for further info). Given that SQL expects a fixed format, it's more reliable to use number_format().

Update: The ADOdb library seems to support prepared statemens. They are normally a simpler and more robust mechanism than injecting values into your SQL code:

$rs = $DB->Execute("select * from table where key=?",array($key));
while (!$rs->EOF) {
    print_r($rs->fields);
    $rs->MoveNext();
}


Stick some single quotes around your values. The 25,50 will be interpreted as two fields, for a start (and I'm pretty sure mySQL won't like 25.50 without quotes either.

$query = sprintf("Insert into table_name (id, value) values ('%d', '$.02f')", $id, $value);

Will result in:

Insert into table_name (id, value) values ('5', '25.50')
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号