Insert into SQL if PHP values blank (NULL) - php

Greets everyone,
I have a PHP form with 40 fields to fill in when a job is completed by a driver. Not all these fields will be filled in. My problem with the new mariaDB update is, the INSERT INTO execution fails on the blanks.
I have set all the SQL default to NULL, but if the page tries to set a "" blank, the SQL doesn't make it a NULL.
Is there anyway way, other than a conditional blank check on every field, to bypass then blanks?
Thanks

try this for your values
$a = isset($_GET['a']) ? $_GET['a'] : null;
if you are using php7.0+ then you may use Null Coalescing Operator
refer

Related

Form trouble: radio button ->yes,no or null

I'm sure I am missing something quite simple, but I have a form with a few yes/no inputs - type=radio. I have made the default NULL. YES is significant, NO is significant and NULL means user has never answered the question. When I UPDATE the db with user's selections, my NULL values are overwritten with 0 even though NO is not selected. I've read that if user doesn't choose either YES or NO that variable is NOT SET, therefore,
$licensedYN = (isset($_POST['licensed'])&&!empty($_POST['licensed']))?$_POST['licensed']:NULL;
$malpracticeYN = (isset($_POST['malpractice']))?$_POST['malpractice']:NULL;
$sqlAdd = $db->query("INSERT INTO temp (licensedYN,malpracticeYN) VALUES ('$licensedYN','$malpracticeYN')");
How do I get NULL to be inserted into DB and not '0'?
To allow NULL as a value in your licensedYN column... Run this query..
ALTER TABLE temp MODIFY licensedYN varchar(255) null;
This would allow you store null values in your db.
In your case you can just remove the quotes from the query and place it in the value as follows:
$licensedYN = (isset($_POST['licensed']) && !empty($_POST['licensed']))? "'{$_POST['licensed']}'" : 'NULL';
$malpracticeYN = (isset($_POST['malpractice'])) ? "'{$_POST['malpractice']}'": 'NULL';
$sqlAdd = $db->query("INSERT INTO temp (licensedYN,malpracticeYN) VALUES ($licensedYN,$malpracticeYN)");
In any case, you should consider working with prepared statements instead of concatenating strings. You will prevent many problems as sql injections, boost the query execution time and will not have headaches with quotation anymore...

How do I insert NULL values for blank fields when using JQuery Serialize?

I have many forms that I am serializing. The data is posted to either an insert.php page or update.php.
If a form input is left blank, I want to insert a NULL value into my database. I'm using mySQL.
It seems like when a form is serialized, any fields that are left blank are sent as value of '' which does NOT insert as NULL into my db.
I can filter out empty inputs before serializing, but this isn't good when a record needs to be updated.
Here's a fiddle of a form that you can at least see that empty inputs are logged as "".
Any advice on how I can set those values to NULL instead?
jsfiddle.net/gabrieleromanato/bynaK/
You can simply at php side check if value is empty use instead null with strlen(...) == 0 condition ( as #PaulSpiegel mentioned in comment of this answer empty will consider that 0 is also empty and will write null to your db ) - http://php.net/manual/en/function.strlen.php
// Example
$value = !strlen($_POST['value']) ? null:$_POST['value'];
// .. save in MySQL

Enter either a date or a null value in database using MySql

I have searched the site and although I have found questions and answers similar I haven't been able to find an answer. After 4 hours of searching I've decided to bite the bullet and ask the question.
I have 4 date fields in a form that aren't required. I would like it to enter a date into the database if one of the fields has an entry or null if any are left blank.
I have an if statement that checks if the value is empty and if so $value = null, otherwise use $value = date("Y-m-d",strtotime($_post['value'])) to convert it to a date and this works well.
The problem is in my query. If I use '$value' it will insert the date correctly but won't insert a null value because using 'null' makes sql think it's a string. If I use just $value the null inserts just fine but the date goes in as 0000-00-00.
Any advice would be very much appreciated
Thanks for the advice so far...
Null is allowed, this is my script...
if(empty($_POST['fp32_original_install_date'])){
$fp32_install = NULL;
}else{
$fp32_install = date("Y-m-d",strtotime($_POST['fp32_original_install_date']));
}
$sql = "INSERT INTO accounts_cstm (id_c, support_c, install_date_c, sware_renewal_date_c, product_key_c, account_status_c, fp32_support_type_c, fp32_support_renewal_date_c, fp32_original_install_date_c) VALUES ('$Guid','$cdr_support', '$cdr_install', '$cdr_renew', '$prod_key', '$account_status', '$fp32_support', '$fp32_renew', $fp32_install)";
If I use in the query $fp32_install a null value goes in just fine but a date goes in as 0000-00-00, if I use '$fp32_install' the date goes in fine but a NULL value goes in as 1970-01-01 (probably because it sees 'NULL' as a string)
If I echo $fp32_install the value is shown as 2012-08-16 and the SQL type for the column is date and the default is NULL
If you are using posted values from a form, then $_POST['value'] will not be NULL.
You should check for empty values instead.
if($_POST['value']=="")
{
$value="NULL";
}
else
{
$value="'".date("Y-m-d",strtotime($_POST['value']))."'";
}
From the behavior you describe, it sounds as if your DATE column is defined with a DEFAULT 0 clause, or you are providing an invalid value.
According to the MySQL documentation:
<snip>
Invalid DATE, DATETIME, or TIMESTAMP values are converted to the “zero” value of the appropriate type ('0000-00-00' or '0000-00-00 00:00:00').
</snip>
It's difficult to diagnose the exact problem without seeing example code. As a starter, I suggest you try echoing out the SQL statement that is being sent to the database.
I have a strong suspicion that the value for the DATE column is going to appear with quotes around it, a string value of 'NULL', rather than the bare keyword NULL.

How do I get PHP to convert a blank field in MySQL to "0"?

I have created a field in MySQL named "pid", which I use in PHP coding at the end of other variable names to indicate which of 7 template designs a user has created. The limit is 7, at which point they are given a message that they have reached their limit.
I have the code working EXCEPT when the field is blank (before user creates the first template). When I hard-code a "0" it works. But, obviously, I need to use the "{pid}" variable to pick up the template sequence in the database.
Here is the PHP:
<?PHP
$pid = {pid};
$total_templates = 7;
if ($total_templates > $pid) {
echo "<a href='create.template.php'><img src='create_template.png'></a>";
} else {
echo "<b style='color: #CC0000'>Your limit of $pid Templates has been reached";
}
?>
How do I get the code to convert a blank field in MySQL to "0" in conjunction with the above code?
If I understand your question, could you not set it to 0 if it is empty()?
$pid={pid};
if(empty($pid))
$pid = 0;
You can also set the default value for that field in mysql. If you are using phpAdmin, go to the table and click the "Change" action and set the default value there. If you need sql command to do this, I can get that for you too.
The best way is to set the default value in mysql to 0. Then you will have no issues.
You could always use intval in order to force it as an integer. See http://php.net/manual/en/function.intval.php.
if ($total_templates > intval($pid))
Although I would just set the default value of the pid field to 0 in MySQL.
You could use the ternary operator to set the $pid value
$pid = ({pid} != '' ? {pid} : '0');
If there is a real value on $pid it'll display it, else it'll display 0, I haven't tested this code.
A better approach would be to set a default value for that field in your SQL.
For more info about the ternary operator

Why an ENUM("0", "1") is saved as an empty string in Mysql?

I have a MYSQL table with an ENUM field named "offset" and some other columns. The field is defined as:
ENUM(0,1), can be NULL, predefined value NULL
Now I have two server. A production server and a development server and the same PHP script used to create and to update the database.
First step: the application create the record witout passing the "offset" in the CREATE query.
Second step: the application ask to the user some data (not the "offset" value), read the row inserted in step one and make an array, update some field (not the "offset" field), create a query in an automated fashion and save the row again with the updated values.
The automated query builder simple read all the field passed in an array and create the UPDATE string.
In both systems I obtain this array:
$values = array(... 'offset' => null);
and convert it in this same query passing the values in the mysql_real_escape_string:
UPDATE MyTable SET values..., `offset` = '' WHERE id = '10';
Now there is the problem. When i launch the query in the production system, the row is saved, in the development system I got an error and the db says that the offset data is wrong without saving the row.
From phpmyadmin when I create the row with the first step, it shows NULL in the offset field. After saving the field in the system which give no errors, it show me an empty string.
Both system are using MySQL 5 but the production uses 5.0.51 on Linux and development use 5.0.37 on Windows.
The questions:
Why one system give me an error an the other one save the field ? Is a configuration difference ?
Why when I save the field which is an enum "0" or "1" it saves "" and not NULL ?
Why one system give me an error an the other one save the field ? Is a configuration difference ?
Probably. See below.
Why when I save the field which is an enum "0" or "1" it saves "" and not NULL ?
According to the MySQL ENUM documentation:
The value may also be the empty string ('') or NULL under certain circumstances:
If you insert an invalid value into an ENUM (that is, a string not present in the list of permitted values), the empty string is inserted instead as a special error value. This string can be distinguished from a "normal" empty string by the fact that this string has the numeric value 0. ...
If strict SQL mode is enabled, attempts to insert invalid ENUM values result in an error.
(Emphasis added.)
strager's answer seems like a good explanation on why your code behaves differently on the 2 environments.
The problem lies elsewhere though. If you want to set a value to NULL in the query you shound use exactly NULL, but you are using mysql_real_escape_string() which result is always a string:
$ php -r 'var_dump(mysql_real_escape_string(null));'
string(0) ""
You should handle this differently. E.g:
$value = null
$escaped_value = is_null($value) ? "NULL" : mysql_real_escape_string($value);
var_dump($escaped_value);
// NULL
Some DB layers, like PDO, handle this just fine for you.
If you want it to be NULL, why don't you do this in the first place:
UPDATE MyTable SET values..., `offset` = NULL WHERE id = 10;

Categories