Home > front end >  PHP different value of a variable if the field is empty
PHP different value of a variable if the field is empty

Time:02-23

I have the following code:

$sn_inlocuit = $_POST['sn_inlocuit'];
$sn_def = $_POST['sn_def'];
        
if(empty($sn_inlocuit) && empty($sn_def))
{
    $ref_echip = "NULL";
} else {
    $ref_echip = rand('100000000','999999999');
}

$sql = "INSERT INTO rapoarte (sn,sn_2,ref_echip) VALUES ('$sn','$sn_2','$ref_echip')";

I have the two fields above which if they are empty I want nothing to be entered in the column of the MYSQL table and if they are not empty, a random number is generated for me and it is entered in the respective column.

The problem is that even if the field is empty, it inserts my random number.

I just attached a piece of code with this condition (if) that doesn't work for me.

Can anyone tell me where I went wrong?

EDIT: I forgot to specify and I missed this, both of my input fields are "multiple input fields" with "Add field button".

<input type="text" placeholder="S/N" name="sn_inlocuit[]">
<input type="text" placeholder="S/N" name="sn_def[]">

Var_dump gave me this:

array(1) { [0]=> string(0) "" } array(1) { [0]=> string(0) "" } 

So in this situation, with multiple input fields how I can do what I want with the If(empty) statement?

CodePudding user response:

Considering those $_POST values are arrays rather than strings, I think using array_filter rather than empty will work in most cases.

if (!array_filter($sn_inlocuit) && !array_filter($sn_def))

As far as other cases, there are some values that could be entered that will evaluate to false and be filtered out by array_filter, e.g. "0", so you may need a more specific filter function if you don't want that to happen. You may also want to trim the values in the arrays before checking them to avoid whitespace-only values which will not be filtered out by array_filter, unless you want those to be considered as actual values.

$sn_inlocuit = array_map('trim', $_POST['sn_inlocuit']);
$sn_def = array_map('trim', $_POST['sn_def']);

CodePudding user response:

for if statement:

$ref_echip = "NULL";

you will set the variable into string. if you mean to set it into boolean, you can use this instead:

$ref_echip = NULL;

and you can put your SQL command to else statement so the SQL command will run while the variable $sn_inlocuit and $sn_def is not empty

  • Related