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

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...

Related

Insert into SQL if PHP values blank (NULL)

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

Leave current value if var is empty in a UPDATE query (sql)

I want not update a record when the variable is empty when executing a UPDATE query in SQL. However, when the variable is filled, the record should be updated.
So in example, the myAge field in the database have currently a value of 20 (type int).
After executing the following query, the record should still be 20.
$age = '';
db_con->query("UPDATE info SET myAge = ".$age." WHERE account_id = 1");
Ps: I know I could check if the variable is empty with PHP, but I was wondering If this could be archieved within SQL?
You could use an IF construct in SQL to check if the value is empty:
$age = mysql_real_escape_string($age);
db_con->query("UPDATE info SET myAge = IF('".$age."' = '', myAge, ".$age.") WHERE account_id = 1");
If the passed PHP variable is empty, you set the old myAge.
Checking in PHP makes more sense, you might save a database query.
The way you are passing that variable to your database is potentially dangerous. If you didn't know about mysql_real_escape_string, look it up NOW.
Better yet, start using a database wrapper that escapes values for you.
I would add the condition into the where, if you only care about one field.
It is not clear what you mean by empty. That could be either NULL or a blank string. My guess is that myAge is a number, so NULL would be "empty":
UPDATE info
SET myAge = ".$age."
WHERE account_id = 1 AND myAge IS NOT NULL;
You can also do this in the SET, if you like:
UPDATE info
SET myAge = (CASE WHEN myAge IS NOT NULL THEN ".$age." END)
WHERE account_id = 1;
This is necessary if you have multiple columns that you want to update like this. I much prefer CASE over IF(), because CASE is ANSI standard and available in most databases.

How to INSERT NULL value from PHP?

Let x is a column of the table t allowing NULL values.
Which value should $value variable take for the following PDO statement to insert NULL value?
$db->prepare("INSERT t SET x=:x")->execute(array(':x'=>$value));
You simply insert it as null:
$db->prepare("INSERT t SET x=:x")->execute(array(':x'=>null));
If you want, you can also add the data type of PDO::PARAM_NULL.
This was asked 9 years ago, so it may no longer be relevant, but SeanWM's existing answer, while it works, does not technically answer specifically what was asked because it does not assign any value to a variable.
Just for completeness:
Inserting the PHP null value into MySQL does result in NULL being inserted into the DB.
$value = null;
$sql = $db->prepare("INSERT t SET x=:x")->execute(array(':x'=>$value));
Output:
Note: be careful NOT to enclose the word null in quotes or it will insert the string "null" instead.

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.

mysql if word match statement

how do i save the data, if
1) the word match Pros, it will be saved to t_pros column
2) the word that not match Pros, it will be saved to t_others column
i heard i can use mysql CASE statement, but dont know how to use it?
table pro:
id t_pros t_others
------------------------
1 Pros 1x
2 Pros 2x
3 voucher
<input type="text" id="t_pros">
$db->query("INSERT INTO pro(t_pros,t_others) VALUES($t_pros, $t_pros)");
So in each row only one of the two columns ever has a value?
In that case, how about:
$column = (preg_match('/^Pros/i', $_POST['t_pros'])) ? 't_pros' : 't_others';
$t_pros = mysql_real_escape_string($_POST['t_pros']);
$db->query("INSERT INTO pro($column) VALUES ($t_pros)");
That is, pick which column based on whether the value begins with 'Pros' or not (just as you indicated), and then just insert into that column, using MySQL's default value (normally NULL) for the other.
First, your input field needs the attribute name="t_pros".
Secondly, this code is open to SQL Injection - read up on it.
The query might look like this:
INSERT INTO pro(t_pros,t_others) VALUES(IF($t_pros = 'Pros', 'Pros', NULL), IF($t_pros = 'Pros', NULL, $t_pros))"
But again, this is not safe. Use mysql_real_escape_string around all variables in your SQL query, or use prepared statements.
if ($t_pros == 'Pros')
$t_pros_col = $t_pros;
else
$t_others_col = $t_pros;
$db->query("INSERT INTO pro(t_pros,t_others) VALUES($t_pros_col, $t_others_col)");

Categories