Values getting rounded up in mysql - php

So basically if I try to insert a value like 2.22 it will get inserted as 2.00 instead of 2.22. I really have no idea why is this happening. I tried changing type of column in mysql but that didn't help at all.
Column in mysql is set to Decimal(7,2).
Here is how i insert the value to database:
$ks = new ks();
$value = $_POST['value']; //value from input field
$data = $ks->getPrepare("INSERT into enties (amount) VALUES (?)");
$data->bind_param("i", $value);
$data->execute();

I figured it out, if you are trying to add decimal numbers to database with prepared statement, you have to use "d" (for double) instead of "i" in bind_param() function.
Example:
$value = "2.22";
$data->bind_param("i", $value);
Value added to database in this case will be 2.00
Example #2
$value = "2.22";
$data->bind_param("d", $value);
Value added to database in this case will be 2.22

Related

PHP to PostgreSQL insert unnested arrays into multiple rows

I have some data in PHP arrays/variables ready to insert into a PostgreSQL table via an INSERT statement.
For a simple example say I have the following information:
$name= 'someName';
$time = array(1,2,3);
$elevation = array(100,200,300);
(In my real application these are double precision and potentially 1,000+ values)
I also have my postgresql table with columns "name","time","elevation"
I want to insert these in a single INSERT statement, and have been given multiple different ways to do this.
Loop and insert one data point (row) at a time.
Use unnest() on the arrays and do a single insert (fastest)
My question is can I pass a single variable name, and the un-nested arrays and have name repeated every row (ever array element), or do I need to construct a repeated array for name the equivalent count() as the other arrays?
An example statement:
*cr_query is a custom PHP pg_query wrapper we use
cr_query($conn,"INSERT INTO sometable (name,time,elevation) VALUES ({$name},{unnest($time)},{unnest($elevation)}););
This would insert into sometable:
ID name time elevation
1 someName 1 100
2 someName 2 200
3 someName 3 300
Am I correct here or do I need to do something else?
EDIT:
Lets say I also have another variable "surface". Surface can be a double value or can be NULL. So I want to insert into the table to look like so:
ID name time elevation surface
1 someName 1 100 50
2 someName 2 200 NULL
3 someName 3 300 100
In PHP, using the method perscribed by klin below an array for surface in the unnest statement would become unnest(array[50,,100]); This throws an error like so:
(Error from my real data)
ERROR: syntax error at or near "," LINE 3: ...-6,5.75E-6,5.75E-6,5.75E-6,5.75E-6]),unnest(array[,,,,,,,,,]... ^
EDIT 2:
Now that all of the "encoding" is working a new problem has popped up. Say the example column "surface" above is type double precision.
Say I am inserting an array, but for this set all of the data is null.
The essential piece is:
unnest(array[null,null,null,null,null,null,null,null,null,null])
However, this array is of type string. Add a single value to it and it becomes the type of that numeric value, but I need to be able to handle this.
My question is: How do I insert an unnested array of all null values into a double precision column? (I tried to cast ::double precision) but it's not possible.
Assuming your cr_query() function is not doing any magic things, your code is going to raise postgres syntax error. You can use unnest but you must prepare proper query text.
Try your code:
$name= 'someName';
$time = array(1,2,3);
$elevation = array(100,200,300);
echo "INSERT INTO sometable (name,time,elevation) VALUES ".
"({$name},{unnest($time)},{unnest($elevation)})"
echo: INSERT INTO sometable (name,time,elevation) VALUES (someName,{unnest(Array)},{unnest(Array)})
Obviously it is not what we want to send to postgres. How to repair this?
$name= 'someName';
$time = array(1,2,3);
$elevation = array(100,200,300);
$timestr = 'array['. implode(',', $time). ']';
$elevstr = 'array['. implode(',', $elevation). ']';
echo "INSERT INTO sometable (name,time,elevation) ".
"VALUES ('$name',unnest($timestr),unnest($elevstr));"
echo: INSERT INTO sometable (name,time,elevation) VALUES ('someName',unnest(array[1,2,3]),unnest(array[100,200,300]));
I think this is correct query. Note that I enclosed text variable '$name' in single quotes.
If you have nulls in your arrays you have to replace all empty strings to 'null' in prepared text for query.
Probably the simplest way to do it is to use str_replace().
As the conversion is getting more complicated it is handy to write a function (say "pgstr()") for that purpose.
function pgstr($array) {
$str =
str_replace('[,', '[null,',
str_replace(',]', ',null]',
'array['. implode(',', $array). ']'));
while (strpos($str, ',,') > 0) $str = str_replace(',,', ',null,', $str);
return $str;
}
$name= 'someName';
$time = array(1,2,3,4);
$elevation = array(100,null,300,null);
$surface = array(null,null,3.24,null);
$timestr = pgstr($time);
$elevstr = pgstr($elevation);
$surfstr = pgstr($surface);
echo
"INSERT INTO sometable (name,time,elevation,surface) ".
"VALUES ('$name',unnest($timestr),unnest($elevstr),unnest($surfstr));";

Issue with value being returned from PDO query

I am experiencing an issue with the values being returned from my PDO statement.
This is my code:
//Execute test
$this->checkConnect();
$stmt = $this->dbh->prepare("SELECT p_id FROM People WHERE lastName = :param1 AND firstName = :param2");
$stmt->bindParam(':param1', $this->lName);
$stmt->bindParam(':param2', $this->fName);
$stmt->execute();
$count = $stmt->rowCount();
//Determine value of test
if($count == FALSE)
{
return FALSE;
}
else
{
$dummyvar = $stmt->fetch();
$this->p_id = implode($dummyvar);
}
When I was going through my database records, I noticed that a certain value was off from what I had input. When I execute a query, it is supposed to grab the value of p_id from the tablePeople. Simple enough. However, what happens is that the number is appended twice to itself. For instance, say p_id is equal to 1. this->p_id will be equal to 11. Or is p_id is equal to 2, the output will be 22. I've executed this query within MySQL and the value is correct. I'm not sure what is happening in my php code. Perhaps something to do with implode? I'm not sure.
Any insight will be appreciated.
Addition: I should also state that p_id is unique, thus only one value can be returned.
First, your fetch statement isn't returning what you think it is. The default output array will have both column name keys, and numeric keys, something like this:
array(
0 => 1,
'pid' => 1,
)
You probably want to get just a numerically-indexed array. Use PDO::FETCH_NUM like this:
$dummyvar = $stmt->fetch(PDO::FETCH_NUM);
Second, if you are going to output more than one field (not in this case obviously) then you have to fix your implode statement. You have to tell it what character to put between the different array values.
$this->p_id = implode(' ', $dummyvar);
For example:
echo implode( ', ', array('a', 'b', 'c') );
> 'a, b, c'
References:
PDOStatement::fetch
implode

PHP MYSQL - empty variable fails on insert

I have an insert statement that inserts variables collected from a form POST on the previous page. If the variables from the form are not filled in it fails on insert (presumably because it is inserting an empty string...) I have the dataype set to allow NULL values - how do I insert null values if the field was left empty from the form POST?
$query = "
INSERT INTO songs (
userid,
wavURL,
mp3URL,
genre,
songTitle,
BPM
) VALUES (
'$userid',
'$wavFile',
'$mp3File',
'$genre',
'$songTitle',
'$BPM'
)
";
$result = mysql_query($query);
The exact manner depends on if you are writing the query or binding parameters to a prepared statement.
If writing your own, it would look something like this:
$value = empty($_POST['bar']) ? null : $_POST['bar'];
$sql = sprintf('INSERT INTO foo (bar) VALUES (%s)',
$value === null ? 'NULL', "'".mysql_real_escape_string($value)."'");
$result = mysql_query($sql);
The main point is that you need to pass in the string NULL (without quotes) if the value should be null and the string 'val' if the value should be "val". Note that since we are writing string literals in PHP, in both cases there is one more pair of quotes in the source code (this makes one pair in the first case, two pairs in the second).
Warning: When inserting to the database directly from request variables, it is very easy to be wide open to SQL injection attacks. Do not be another victim; read about how to protect yourself and implement one of the universally accepted solutions.
For what I understand when something is not filled the post variable is not set as an empty value but rather not set at all so in php you'd do for example:
$genre = isset($_POST['genre']) ? $_POST['genre'] : NULL;
Here's how I do it. I don't like sending anything to an SQL query right from POST (always sanitize!) in the following cas you just run through the POST vars one by one and assign them to a secondary array while checking for 0 length strings and setting them to NULL.
foreach ($_POST as $key => $value) {
strlen($value)=0 ? $vars[$key] = NULL : $vars[$key] = $value
}
Then you can build your SQL query from the newly created $vars[] array.
As Jon states above, this would be the place to also escape strings, strip code and basically do all your server side validation prior to data being inserted into the db.

MYSQL/PHP How do I insert a null value?

I'm having problems updating records to contain NULL values - in particular, a field which is of type Date.
I'm using prepared statements and I've tried the following:
// Fails
$value = NULL;
// Fails
$value = "";
// Fails
$value = "NULL";
all 3 of the above result in a date of 1969-12-31 being entered (0). How do I insert NULL values?
Did you read the following question/answer: using nulls in a mysqli prepared statement
That seems to be the same issue. Correct me if I'm wrong?

passing a null value to mysql database

A user fills out a form and if they choose to not fill out a field that is not required php does this:
if($_SESSION['numofchildren']=="")
$_SESSION['numofchildren']=null;
But when I use the session variable in a mysql query, the result is not null, but is 0. The column is a tinyint(4) that allows NULL.
Why am I getting a 0 instead of NULL?
Probably because PHP doesn't convert 'null' into 'NULL'. You are probably just inserting an empty value.
INSERT INTO TABLE (`Field`) ('')
You probably have the default for the column set to '0', and that means that it will insert a 0 unless you specify a number or NULL
INSERT INTO TABLE ('Field') (NULL)
To fix this, check for Null Values before you do the query.
foreach($values as $key => $value)
{
if($value == null)
{
$values[$key] = "NULL";
}
}
I have a feeling that prepared statements will have the foresight to do this automagically. But, if you are doing inline statements, you need to add a few more things.
MySQL values must have quotes around them, but Nulls don't. Therefore, you are going to need to quote everything else using this
foreach($values as $key => $value)
{
if($value == null)
{
$values[$key] = "NULL";
}
else
{
// Real Escape for Good Measure
$values[$key] = "'" . mysql_real_escape_string($value) . "'";
}
}
Then, when you create the statement, make sure to not put quotes around any values
$SQL = "INSERT INTO TABLE (Field) VALUES(".$values['field'].")";
turns into
$SQL = "INSERT INTO TABLE (Field) VALUES("Test Value")";
or
$SQL = "INSERT INTO TABLE (Field) VALUES(NULL)";
Have a look at the table definition for whichever table you're inserting into. The 'default' value for that field is probably set to zero.
The version of MySql you are using is quite important in determining precisely how MySql treats Data Type Default Values.
The above link says:
For numeric types, the default is 0,
with the exception that for integer or
floating-point types declared with the
AUTO_INCREMENT attribute, the default
is the next value in the sequence.
You all where probably right, but all I had to do is put quotes around the null.
if($_SESSION['numofchildren']=="")
$_SESSION['numofchildren']='NULL';
I had the same problem some minutes ago, but then I figured it out. In my case I was making the query with the NULL variables between quotes like these ", '. Let me explain myself...
This is what you want to do:
INSERT INTO `tbl_name` (`col1`, `col2`) VALUES (NULL,"some_value");
So if you want to use a NULL variable it should be "NULL", like this:
$var1="NULL"; $var2="some_value";
Now, if you want to use $var2, you will type '$var2' in the query, but you shouldn't do the same for $var1:
INSERT INTO `tbl_name` (`col1`, `col2`) VALUES ($var1,'$var2');
If you put $var1 between quotes, you'll get a 0 instead NULL.
For me it didn't work to put NULL var in database, I used var char(2).
So I just made 2 queries. This way it will work 100%. For your example it would be:
if($_SESSION['numofchildren']=="")
{
$updatequery="
UPDATE table
SET table1='$value', table2='$value2', numofchilrdrentable=(NULL)
";
}
else
{
$updatequery="
UPDATE table
SET table1='$value', table2='$value2', numofchilrdrentable='$_SESSION[numofchildren]'
";
}
$updatequeryresult=mysql_query($updatequery) or die("query fout " . mysql_error() );
edit: var char -> var char(2)
null parsed to string becomes 0. Try using is_null() to check that first and place NULL instead of 0 in the query.
Or, try using PDO and PDO::prepare for a perfect and hacker-safe query.
It's very confusing especially when values were posted from a web form. I do it like that:
We assume you need a database field named 'numofchildren' that will accept possible values: NULL, 0, 1, 2.., etc. up to 99 and default should be the SQL NULL value.
SQL field should be defined as:
.. `numofchildren` INT( 2 ) NULL DEFAULT NULL
When you insert your data for the NULL values you pass strings like 'NULL' and look for them when looping the incoming data. The other values you just cast to integers:
foreach ($data as $v) {
$v['numofchildren'] = !isset($v['numofchildren']) || $v['numofchildren'] === 'NULL' ? '(NULL)' : (int) $v['numofchildren'];
$q = "INSERT INTO tablename (numofchildren) VALUES ({$v['numofchildren']}) ";
...
}
Note that {$v['numofchildren']} in SQL query is not surrounded with single quotes because you do not pass strings but integers (0,1,2..) or SQL NULL.
I believe it's clear and short and covers the issue.
if you want set NULL for any column in DATABASE
at first
You should check is_null for that column
secuond :if the variable you want
Set to null code you must insert "null" in double quote then submit to database
If you set null to double quote("") nothing, nothing will be sent and the database will get an error
for example :
function insert_to_db($var){
...
sql="INSERT INTO table VALUES($var)"
...
}
when you use in code with "" and without "" =>
function insert_to_db(null)// error : INSERT INTO table VALUES()
correct:
function insert_to_db("null")//its ok

Categories