How can I add to my database information from a form if I have mandatory and optional fields? So far I have only done a few inserts but in all of those all the information was always present. In this case I am making a contact form where the name, surname and cellphone number are mandatory and where all the others are optional.
Also the person's information (name, surnames, nickname) goes into a table while the numbers (home, work, fax, cell etc) goes into another table.
A example (of another app) code I have used for POST:
jQuery (Ajax)
$("#btnAceptar").click(function() {
var codigolab = $('#txtNumLab').val(),
capacidad = $('#txtCapacidad').val(),
carrera = $('#txtCarrera').val(),
ubicacion = $('#txtUbicacion').val();
var request = $.ajax({
url: "includes/functionsLabs.php",
type: "post",
data: {
'call': 'addLab',
'pCodigoLab':codigolab,
'pCapacidad':capacidad,
'pCarrera':carrera,
'pUbicacion':ubicacion},
dataType: 'html',
success: function(response){
$('#info').html(response);
}
});
});
PHP I use in this example to add to the database
function addLab(){
if(isset($_POST['pCodigoLab']) &&
isset($_POST['pCapacidad']) &&
isset($_POST['pCarrera']) &&
isset ($_POST['pUbicacion'])){
$codigolab = $_POST['pCodigoLab'];
$capacidad = $_POST['pCapacidad'];
$carrera = $_POST['pCarrera'];
$ubicacion = $_POST['pUbicacion'];
$query = "INSERT INTO labs VALUES" . "('null', '$codigolab', '$capacidad', '$carrera','$ubicacion', '1')";
$result = do_query($query);
echo "<p>¡El laboratorio ha sido añadido exitosamente!</p>";
}
}
In this case where I am making some fields mandatory and others not I need to insert into different tables, to add another insert into that query do I just use a AND or something like that?
Also if the user doesn't input anything in some fields do I leave the optional fields out of the isset statements? How would those variables be declared if I cannot be certain if they're going to be used?
Sorry if I am making this a bit hard to follow I am a bit confused and english is not my main language.
Thanks in advance.
FIDDLE OF the actual code:
Pressing Guardar button displays the fields that are mandatory the others are optional.
Thanks