bindParam and NULL int values - php

I am using bindParam to set values for a MySQL insert. The column in question is an INT (11). It has a default of NULL and null is allowed. However, using bindParam it always receives a 0. I have confirmed that my $_POST['value'] is indeed null.
if(isset($_POST['value'])){
$stmt = $db->prepare("INSERT INTO table (column) VALUES (:column)");
$stmt->bindParam(':column',$_POST['value'], PDO::PARAM_INT);
$stmt->execute();
}
It keeps inserting a '0' instead of NULL if the POST value was ''.

You should be matching the complete case (Answer and type) with === (Read More)
Which most likely means that your value is not null like you presume it is.
Ensure it is by checking (pseudo code below):
if(VALUE !=== NULL) {
value = null
}
But you get the idea there? If not just comment :-)
And as aldanux mentioned in his comment, you have to wrap the column in backticks as it is a reserved word:
INSERT INTO table (`column`) VALUES (:column)

Related

php mysql prepared statement pass 0 into decimal column where NULLs are allowed

I have a Mysql table with a decimal column that allows NULLs. If I pass 0 as double in a PHP's prepared statement, my 0 turns NULL in the Mysql column.
How can I get the value 0 instead of NULL?
PS: I use the following code to insert the value
$query2 = "insert into TableName
(Id, anotherId, date,
`MinValue`, `MaxValue`,
`oneMoreId`, `Comment`)
values
(?, ?, '2016-06-23',
?, ?,
?, ?)";
$stmt = $connection->prepare($query2);
$stmt->bind_param('iiddis', $Id, $anotherId,
$minValue, $maxValue, $oneMoreId,
$comment);
$stmt->execute();
EDIT: after answer by #YourCommonSense, I figured there was an error in my code. Above the lines that I posted, I had a change of value from 0 to NULL. My fault, sorry, guys!
If I pass 0 as double in a PHP's prepared statement, my 0 turns NULL in the Mysql column.
This is not true.
If you pass 0, then it gets stored as 0.
But if you pass NULL, then it gets stored as NULL.
Therefore, you are passing NULL value, not 0.
Check your values and cast them if necessary.

Integer inserting as 0 instead of NULL

When I insert a NULL into a MYSQL INTEGER field via a PHP prepared statement it inserts as 0.
I have searched for similar questions and have update my code but am still having the problem.
In my code, if a text box sends an empty string to PHP; PHP converts it to NULL ie.
$v3 = (strlen($v3)<1 ) ? NULL : $v3;
As an example, a result in the UNIT column could be NULL.
The prepare statement
$stmt = $mysqli->prepare("INSERT INTO address ( `PERSON`, `TYPE`, `UNIT`, `STREET_NUM`, `STREET`, `STREET_TYPE`, `SUBURB`, `STATE` ) VALUES (?,?,?,?,?,?,?,?)"));
Bind the parameter as an integer
$stmt->bind_param('isiissss',$p, $add_type[$a], $unit[$a], $street_num[$a], $street_name[$a], $street_type[$a], $suburb[$a], $state[$a]);
In MYSQL, address.unit is NULLABLE and has no default value.
If I insert directly into the table and omit a value for the unit column; NULL is stored. Which I expected.
I suspect that the bind_param function changes NULL to 0 if the datatype for the column is specified as 'i' (integer), because NULLs passed to VARCHAR columns are stored as NULL.
Am I correct and if so how should I pass a NULL to the integer column?
To simplify my question (and because I didn't think it would be relevant) I omitted that the values where passing through a $mysqli->real_escape_string function and after some testing I found that it converts a NULL to an empty string
$test = "";
$test = (strlen($test)<1 ) ? NULL : $test;
var_dump($test); // null
echo "<br>";
$test = $mysqli->real_escape_string($test);
var_dump($test); // string '' (length=0)
This does not solve my problem but it does answer this question

Setting variable's database value to NULL instead of empty string

In my SQL database there're many fields like this:
Field Type:Text Null:Yes Default:NULL
My INSERT looks like this:
INSERT INTO tbl (col,col,col,...) VALUES ('val','val','val',...)
Now, those quotes in my INSERT statement's values are inserting '' (empty string) in to the database when what I really want is nothing (NULL).
So I tried
if (isset($_POST['title'])) {$newTitle = mysql_real_escape_string(trim($_POST['title']));} else {$newTitle = NULL;}
and that just inserts 'NULL' - the string containing the word NULL.
What can I do to be certain my NULL values are inserted properly?
What you have is fine, but you need to combine it with a prepared statement...
// prepare the statement
$stmt = $mysqli->prepare("INSERT INTO tbl (title, x,y,z) values (?,?,?,?)");
$stmt->bind_param($newTitle, $x,$y,$z);
$x = 'hello, world';
// execute prepared statement
$stmt->execute();
If x or newTitle are NULL, they will be NULL in the DB
You can try by adding a NULL without the quotes example below:
INSERT INTO tbl (col,col,col,...) VALUES (NULL,'val','val',...)
Also make sure the column that you want to have a pure null must have the allowed NULL ticked.
Don't specify the field in INSERT INTO or provide a value.
If you have 3 fields, f1 f2 f3
And you
INSERT INTO tbl (f1, f3) VALUES ('something', 'something')
Then f2 will not be inserted and default to null.
I use '0' instead of null. When you use if statements you can run queries like
if($row['f2'] == 0){...
Rather than null :)

PHP/MySQL Insert null values

I'm struggling with some PHP/MySQL code. I am reading from 1 table, changing some fields then writing to another table, nothing happens if inserting and one of the array values is null when I would like it to insert null in the database (null values are allowed for the field). It looks a bit like this:
$results = mysql_query("select * from mytable");
while ($row = mysql_fetch_assoc($results) {
mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', {$row['null_field']});
}
Not every row has a null value and in my query there are more fields and 2 columns which may or may not be null
This is one example where using prepared statements really saves you some trouble.
In MySQL, in order to insert a null value, you must specify it at INSERT time or leave the field out which requires additional branching:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', NULL);
However, if you want to insert a value in that field, you must now branch your code to add the single quotes:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', 'String Value');
Prepared statements automatically do that for you. They know the difference between string(0) "" and null and write your query appropriately:
$stmt = $mysqli->prepare("INSERT INTO table2 (f1, f2) VALUES (?, ?)");
$stmt->bind_param('ss', $field1, $field2);
$field1 = "String Value";
$field2 = null;
$stmt->execute();
It escapes your fields for you, makes sure that you don't forget to bind a parameter. There is no reason to stay with the mysql extension. Use mysqli and it's prepared statements instead. You'll save yourself a world of pain.
I think you need quotes around your {$row['null_field']}, so '{$row['null_field']}'
If you don't have the quotes, you'll occasionally end up with an insert statement that looks like this: insert into table2 (f1, f2) values ('val1',) which is a syntax error.
If that is a numeric field, you will have to do some testing above it, and if there is no value in null_field, explicitly set it to null..
For fields where NULL is acceptable, you could use var_export($var, true) to output the string, integer, or NULL literal. Note that you would not surround the output with quotes because they will be automatically added or omitted.
For example:
mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', ".var_export($row['null_field'], true).")");

Using NULL value in INSERT or UPDATE with prepared statements

Sometimes I need to insert into the table some null values, or update them setting the value to NULL.
I've read somewhere in the Postgres documentation that this can't be done, but can be tricked with the default value:
pg_query("INSERT INTO my_table (col_a, col_b) VALUES ('whatever', default)
I know that in this example I'll have the same result with:
pg_query("INSERT INTO my_table (col_a) VALUES ('whatever')
But the problem comes with prepared statements:
pg_prepare($pgconn, 'insert_null_val', "INSERT INTO my_table (col_a, col_b) VALUES ($1, default)");
pg_exec($pgconn, 'insert_null_val', array('whatever'));
//this works, but
pg_prepare($pgconn, 'insert_null_val', "INSERT INTO my_table (col_a, col_b) VALUES ($1, $2)");
pg_exec($pgconn, 'insert_null_val', array('whatever', 'NULL'));
//insert into the table the string 'NULL'.
//instead using array('whatever', '') it assume the col_b as empty value, not NULL.
The same problem applies to update statements.
I think there is a solution, because pgmyadmin can do that (or it seems like it can).
If you are wondering why I need to play with null values in my tables, let me throw an example (maybe there is a way better then the null value?):
Assume I have the users table with an email column, which can be empty, but has a unique index. 2 empty emails are equal and violate the unique constraint, while 2 NULL values are not equal and can coexist.
Use the php's literal NULL as a parameter:
pg_prepare($pgconn, 'insert_null_val', "INSERT INTO my_table (col_a, col_b) VALUES ($1, $2)");
pg_query($pgconn, 'insert_null_val', array('whatever', NULL));

Categories