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 example, 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 withprintf()and the%fmodifier. Replacing$.02fwith%sshould 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 usenumber_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: