简体   繁体   中英

Form validation. Is $_POST if NOT null possible?

Is it possible to tell php to NOT post data if the form field is null?

right now my post variables in my insert.php page look like this:

fname = $_POST['firstname'];
lname = $_post['lasname'];

sql = "UPDATE profile SET first='.$fname.', last='.$lname.' WHERE id='.$id.'";

If my form fields are empty or null, I'd like the $fname $lname not to post. What would be the best method to do this?

Currently when i submit an update, if those fields are empty they update the entire table with empty rows if nothing is inserted.

You could use something like this for each field:

$fname = empty($_POST['firstname']) ? null : $_POST['firstname'];

This will set $fname to null if the form field does not exist or the input was empty. Otherwise, it will use the original value.

Update

If you want to only update fields that aren't null, you'll need to add some extra logic:

if($fname !== null && $lname !== null) {
    // update both
}
else if($fname !== null) {
    // update just fname
}
else if($lname !== null) {
    // update just lname
}

Is it possible to tell php to NOT post data if the form field is null? It isn't PHP who is posting data, it is your browser the moment you hit the submit button of the form. In order to prevent this from happening when the fields are empty, you will have to use something client-sided (javascript), which first validates if the fields are indeed filled in before the form is submitted.

This is how I understand your question though. If you don't want to create the SQL query when the $_POST variables are empty, then simply use an if condition or a ternary operator.

I'd do this:

$fname = isset($_POST['firstname']) && strlen($_POST['firstname']) > 0 ? $_POST['firstname'] : null;

This way, $fname will be defined to the $_POST['firstname'] value if the variable is set and not empty, otherwise it will be null

By the way, if you're working inside double quotes ( " ), there's no need to use a dot to add values to the $sql string. Even more, your syntax is wrong. This is a working way to do it:

$sql = "UPDATE profile SET first='$fname', last='$lname' WHERE id='$id'";

You should NOT use this kind of SQL-query generation. It's vulnerable to SQL injections. Better use PDO or MySQLi parametrized queries.

And, by the way, if you want to deny the insertion if a value is empty, you better do it when creating the MySQL table (assigning a not null property to the column). For example:

CREATE TABLE user(
    first VARCHAR(50) NOT NULL,
    last VARCHAR(50) NOT NULL
)

** EDIT: If I'm understanding well, this is that you want:

$valuesToAdd = "";
// Concatenate values to the query if they are defined
if (isset($_POST['firstname']) && strlen($_POST['firstname']) > 0) $valuesToAdd .= "first = '{$_POST['firstname']}',";
if (isset($_POST['lastname']) && strlen($_POST['lastname']) > 0) $valuesToAdd .= "last = '{$_POST['lastname']}',";
// Repeat for any other values...

// By default, the SQL string is empty
$sql = "";

// If changes were made...
if (strlen($valuesToAdd) > 0) {
    // Remove the last ","
    $valuesToAdd = substr($valuesToAdd, 0, strlen($valuesToAdd)-1);

    // Generate the SQL string with the values which will be added
    $sql = "UPDATE profile SET {$valuesToAdd} WHERE id='{$id}'";

    // echo $sql; die;
}


// Check if the SQL string is not empty
if (strlen($sql) > 0) {
    // Here the SQL has been generated, use it for a SQL query...
    // $con = mysql_connect(...); .....
}
$fname = $_POST['firstname'];
$lname = $_POST['lastname'];

$sets = array();

if(trim($fname)) {
  $sets[] = "first = '".mysql_real_escape_string($fname)."'";
}
if(trim($lname)) {
  $sets[] = "last = '".mysql_real_escape_string($lname)."'";
}

if($sets) {
  $sql = "UPDATE profile SET ".implode(", ", $sets)." WHERE id='".mysql_real_escape_string($id)."'";
}

Remember to properly escape your values before you glue them to SQL.

You need form validation. Easy solution will not allow empty fields save in db and prevent SQL-injections .

Easy solution :

$fname = isset($_POST['firstname']) and nameIsValid($_POST['firstname'])
    ? $_POST['firstname'] : false;
$lname = isset($_POST['lastname']) and nameIsValid($_POST['lastname'])
    ? $_POST['lastname'] : false;

if (false === $fname or false === $lname) {
    // report about not valid form fields
} else {
    $dsn = 'mysql:dbname=yourdb;host=yourhost;charset=utf8';
    $dbh = new PDO($dsn, 'user', 'pass');
    $sql = "UPDATE profile SET first = :fname, last = :lname WHERE id = :id";

    $stmt = $dbh->prepare($sql);
    $stmt->execute(array(':fname' => $value, ':lname' => $lname, ':id' => $id));
}

/**
 * Validation names for empty values
 *
 * @param string $name First name or last name
 * @return bool
 */
function nameIsValid($name) {
    return '' !== $name;
}

But be aware of XSS-injection . For example somebody can save in your db Fist name:

<script>alert('Woohoo! You have vulnerability!');</script>

And next time, when you print First name of the user, everyone will see message about vulnerability :)

You may decide implement more strict validation rules, which will not allow names like "asfyua23807*^2#" , "-2*&%$9837239askHF" or XSS-injections. In this case you should modify nameIsValid() function.

Safe solution:

/**
 * Validation names and prevent XSS-injections
 *
 * @param string $name First name or last name
 * @return bool
 */
function nameIsValid($name) {
    $pattern = '/^[\.a-z-]+$/i';
    return (bool) preg_match($pattern, $name);
}

This logic allow names containing Az . - symbols: J.Jameson , Jackson-Piterson , JOHn , smIth , etc . For more strict validation rules check Official PHP Regular Expressions manual .

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