简体   繁体   中英

Posting a form with optional and mandatory fields

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

Let's say I have the fields name , email , note where the first 2 are required and the last one is not.

Here is one way to do it:

<?php
$error = array();
if (!isset($_POST['name']))
{
    $error[] = "The field name was not filled!";
}

if (!isset($_POST['email']))
{
    $error[] = "The field email was not filled!";
}

if (sizeof($error) == 0)
{
    // insert the data
    $query = sprintf("INSERT INTO users VALUES ('%s', '%s', '%s')",
                     mysql_real_escape_string($_POST['name']),
                     mysql_real_escape_string($_POST['email']),
                     mysql_real_escape_string((isset($_POST['note']) ? $_POST['note'] : '')));

    $result = do_query($query);
    echo "<p>¡El laboratorio ha sido añadido exitosamente!</p>";
}
else
{
    // print the error
    foreach ($error as $msg)
    {
        echo $msg, "<br>\n";
    }
}

For note I used a ternary operator:

isset($_POST['note']) ? $_POST['note'] : ''

Which essentially is a one liner if/else, which could have been written as:

if (isset($_POST['note']))
{
    $note = $_POST['note'];
}
else
{
    $note = '';
}

Also make sure you sanitize your data in your case using mysql_real_escape_string to prevent SQL Injection.

One way to do it could be (I'm not an expert at PHP, so others may have a better solution):

$codigolab = isset($_POST['pCodigoLab']) ? "'" . $_POST['pCodigoLab'] . "'" : NULL;
$capacidad = isset($_POST['pCapacidad']) ? "'" . $_POST['pCapacidad'] . "'" : NULL;
$carrera = isset($_POST['pCarrera']) ? "'" . $_POST['pCarrera'] . "'" : NULL;
$ubicacion = isset($_POST['pUbicacion']) ? "'" . $_POST['pUbicacion'] . "'" : NULL;

This would mean that you would need to remove the single quotes from your SQL.

One word of warning: With your SQL, please look into prepared statements. As is, it would be easy to send pUbicacion = " -');DELETE labs;-- " (Or something similar.) This would allow a person to use a SQL injection and either alter or delete your data.

Edit: Add link to PHP's mysqli_prepare page: PHP::mysqli::prepare

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM