R9102
R9102

Reputation: 727

How to set default value if the field is empty.-php

I want to set default value if the field is empty.

I have a text field with reset button with that, and also i want to set default value in that field.

If user wants to change the field value he can click on reset and enter new value and click on save.

If field is empty by default it should be default value.

on click of save its getting saved in database.

Here is my code

<td>
<input id="default_fromMail" name="default_fromMail" type="email" value="<?php echo isset($item['default_fromMail']) ? $item['default_fromMail'] : ''; ?>"
size="50" class="code" placeholder="<?php _e('', 'custom_table_example')?>"   /> 
<input  type="button" value="Reset" id="default_from_button" name="openLab5" />
</td>

As of now its getting saved into database. But empty field is saved as it is(empty value)

I tried setting default value in table it self but still its not working.

Below is my db structure enter image description here

i need xyz@gmail as default if the value is empty.

Upvotes: 0

Views: 2701

Answers (2)

Simas Joneliunas
Simas Joneliunas

Reputation: 3118

you should check the value in the code that saves the field (form) value in the database. If this field is empty, you should pass it the default value.

$defaultMail = empty($_POST['default_fromMail']) ? 'xyz@gmail' : $_POST['default_fromMail'];

And then save the $defaultMail value to the database.

Upvotes: 2

Artem Ilchenko
Artem Ilchenko

Reputation: 1035

In handler form code use this:

$email = (empty($_POST['default_fromMail']) ? 'xyz@gmail' : $_POST['default_fromMail'];

And then write $email to DB.

This variant better than set default value in DB column, 'cause if you want change default value, you need change only variable value against change table structure.

Upvotes: 2

Related Questions