sprintf changing the number format - php

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 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')

Related

PHP Mysqli Interpreting Array Value As Mathematical Equation

I can't seem to escape an array value when attempting to upload an array value into a database. PHP is interpreting it as a mathematical equation instead of the 'minus' symbol to which is what I wish to upload. It's resulting in error and failing to upload instead.
$aDataTableDetailHTML[0]['OTG'] prints out as the minus symbol: -
$sql = "INSERT INTO MYTABLE (status) VALUES (".$aDataTableDetailHTML[0][OTG].")";
My understanding is that I need to 'escape' the specific value in order for PHP to ignore processing it as a math value, however, when I do this it resolves as blank or nothing.
$OTG = mysqli_real_escape_string($con, $aDataTableDetailHTML[0]['OTG']);
I'm guessing this is painfully easy and I'm missing something obvious. Any suggestions?
It's not PHP mis-interpreting your value, it's MySQL. You query as currently written will get sent to MySQL as:
INSERT INTO MYTABLE (status) VALUES (-)
which is invalid MySQL. You just need to put the value into quotes:
$sql = "INSERT INTO MYTABLE (status) VALUES ('".$aDataTableDetailHTML[0][OTG]."')";
That will prevent MySQL interpreting it as anything other than a string.

Column count doesn't match value count at row 1 (columns and values are equal)

I'm getting the error: Column count doesn't match value count at row 1
I think, normally this error occurs if the count of the columns and the values aren't equal, but in my code they are...(3).
This is my php code:
$tempsongtitel = $_POST['songtitle'];
$tempinterpret = $_POST['interpret'];
$templink = $_POST['link'];
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link) values ('$tempsongtitel, $tempinterpret, $templink')") or die(mysql_error());
You missed some quotes. Should be:
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link) values ('$tempsongtitel', '$tempinterpret', '$templink')") or die(mysql_error());
Otherwise, you were trying to insert all three POST values into the first field.
Moreover, the mysql_ extension has been deprecated and is on the way out and is highly discouraged, especially if you are creating new software.
AND I'll presume you are first sanitizing your data? You're not really taking user input and placing it directly into the database, are you? Even if you don't do any data validation, you should escape your data in the query... easiest and most foolproof way to do that is by using parameterized queries.
The root cause is that your values are all in one set of quotes instead of quoted individually. I think this is a pretty common error, and in my experience it is an easy mistake to make, but not immediately obvious when scanning over your code. You can fix it like this (quick fix, still using deprecated mysql, but with post values escaped):
$tempsongtitel = mysql_escape_string($_POST['songtitle']);
$tempinterpret = mysql_escape_string($_POST['interpret']);
$templink = mysql_escape_string($_POST['link']);
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link)
values ('$tempsongtitel', '$tempinterpret', '$templink')") or die(mysql_error());
If you can, it would be much better to update your code to use PDO. You could use a prepared statement like this:
$stmt = $pdo->prepare("INSERT INTO tMusic (Songtitel, Interpret, Link) VALUES (?, ?, ?)");
$stmt->bindValue(1, $tempsongtitel);
$stmt->bindValue(2, $tempinterpret);
$stmt->bindValue(3, $templink);
$stmt->execute();
Among the many benefits of using this database extension rather than the old mysql functions it should not be possible to make an error like this in your code. In the prepared statement, there are no quotes around the parameter markers, so if you have VALUES ('?, ?, ?'), or even VALUES ('?', '?', '?') You would get bind errors when trying to bind the values, and the problem would become apparent pretty quickly.
I've found that, even though it's not 100% necessary and it's more time consuming, properly quoting and backticking EVERYTHING helps prevent this from happening.
$myQuery = "INSERT INTO `tMusic` (
`Songtitel`,
`Interpret`,
`Link`
) VALUES (
'$tempsongtitel',
'$tempinterpret',
'$templink'
);";
$runQuery = mysqi_query($DBi, $myQuery) or die(mysqli_error($DBi));
The formatting you use is up to you but this helps me make sure I have a one to one relationship and that I've quoted everything.
Of course that's using mysqli_* in place of the deprecated mysql_* functions AND that's assuming you've set $tempsongtitel, $tempinterpret and $templink properly.

Inserting $variable or $_POST value into mysql table [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
My question concerns why one piece of code works and two that does not, and how i can get the code that does not work to work.
The code that works:
mysql_select_db("webuser1", $con);
mysql_query("INSERT INTO users (column 1, column2) VALUES ('value1', 'value2')");
mysql_close($con);
Code no1 that does not ($var1 contains 'value1' etc.):
mysql_select_db("webuser1", $con);
mysql_query("INSERT INTO users (column 1, column2) VALUES ($var1, $var2)");
mysql_close($con);
And code no2 that does not work ($_POST['value1'] contains 'value1' etc.):
mysql_select_db("webuser1", $con);
mysql_query("INSERT INTO users (column 1, column2) VALUES ($_POST['value1'], $_POST['value2'])");
mysql_close($con);
Am i not supposed to be able to insert $var or $_POST in mysql? I hope you do not find this Q stupid but i have been looking around for solutions but i have not understood them.
Thank you
In SQL, string values need to be quoted:
VALUES ('value1', 'value2')"
When you use variables:
VALUES ($var1, $var2)");
They are not quoted … unless the quotes are in the values themselves.
So if $var1 = 'value1'; $var2 = 'value2' then (after the variables are interpolated in your string) your SQL looks like this:
VALUES (value1, value2)"
You could resolve your immediate problem by adding quotes:
VALUES ('$var1', '$var2')");
but this doesn't fix your major security vulnerability and lets your data break the query in different ways.
You should avoid creating SQL statements by assembling strings from variables. This way leads to SQL Injection security holes. Use an interface that supports bound arguments. They will handle quoting and escaping for you.
mysql needs single quotes to enclose a string... so you would need something like this:
mysql_query("INSERT INTO users (column 1, column2) VALUES ('".$_POST['value1']."', '".$_POST['value2']."')");
for everything that is not a string you won't need the single quotes (')
as mentioned before you should not forget to escape strings that you want to put into the database.
for example use prepared statements. by binding the parameters it is ensured that your passed value is of the type you specified within the prepared statement.
Seems like you're not escaping and quoting your arguments to mysql properly.
To insert variables in MySQL you need to escape them at least: $var = mysql_real_escape_string($_POST['variable']) and then ".. VALUES ('".$var."')"
You should also probably consider using libraries for connecting to MySQL like DOCTRINE: http://www.doctrine-project.org/ that handles this for you.
Use this solution, its 100% works
mysql_query("INSERT INTO users (column 1, column2) VALUES ('{$_POST[value1]}', '{$_POST[value2]}')");
when you use {}, you dont need write value in ' '
mysql_select_db("webuser1", $con);
mysql_query("INSERT INTO users (column 1, column2) VALUES ('$var1', '$var2')");
mysql_close($con);
When not using Apostrophes around values, it is supposed to be non string value.
Your variables are not recognized as variables. They are a part of your string.
Try:
mysql_query("INSERT INTO users (column 1, column2) VALUES ('".$var1."', '".$var2."')");
Same for your second problem.
Because the POST variables have ' in them, you have to concatenate instead.
I.E.
mysql_query("INSERT INTO users (column 1, column2) VALUES (".$_POST['value1'].", ".$_POST['value2'].")");
Or
mysql_query("INSERT INTO users (column 1, column2) VALUES ({$_POST['value1']}, {$_POST['value2']})");
It's also a good idea to put quotes around the variables, in case its empty (or a string rather than an integer)
$var1=$_POST['variable_name1'];
$var2=$_POST['variable_name2'];
$q="INSERT INTO `users` (`column 1`, `column2`) VALUES ($var1, $var2)";
$result=mysql_query($q);

MySQL and PHP - insert even if variable is blank?

I have a MySQL statement that inserts some variables into the database. I recently added 2 fields which are optional ($intLat, $intLng), but I would like to include them in the insert statement if entered:
$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long',
'$intLat', '$intLng')";
mysql_query($query);
Just use one insert, and if the variable is empty it will post to the database empty
Disagree with Michael Stevens; if the values are optional, they should be NULL in the database. However, since you have them quoted, they will be inserted as empty strings. That would be bad from a data-sanity perspective.
So... how to do it? Spend a few moments writing (or finding...) a function that takes an associative array as input, and generates the query. Key ingredients: array_keys, implode and mysql_real_escape_string. The PHP Manual is littered with these :)

MySQL/PHP - Would putting quotes around numbers break any queries?

I want to have a generic PHP function that builds a mysql query based on the parameters of the function. Since it is generic the query may sometimes ask for id=123 or name='Bob'. I test out some queries with quotes around numbers, even stuff like WHERE id > '50' + 7 and it worked but I have my doubts that this won't cause trouble down the road. I guess if this is really an all purpose function it should be able to handle dates and whatever other datatypes there are. So what would be the best way to form these queries safely?
Quotes around values are fine for any type as long as your query sticks to mySQL. The way the values will be treated will depend on the type of the field it's compared against. If necessary, they will be converted automatically.
As an aside, you may want to look into database wrappers that offer prepared statements like PDO. Apart from other advantages, they will take care of the quoting - and the escaping of incoming data - themselves.
An example from the manual:
<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindValue(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR);
$sth->execute();
?>
No quotes do no harm to any of data type. Because, mysql engine will convert it to corresponding columns' data type.
Empty quotes in mysql inserts act like they are interpreted as a string value.
If you are using a function for generating an insert for a mysql INT column and end up with
IntColumn = ''
you could get a type error.
ERROR 1366: 1366: Incorrect integer value: '' for column 'IntColumn' at row 1
You will want to filter out INT columns setting an empty value or put unquoted null instead of the empty quotes.
IntColumn = null

Categories