-1

I'm starting to learn PHP and have the code below, which includes a connection to the database from a db.php file, which then runs a query which uses HTML form data that is added to a MYSQL database.

In the code below there is an if statement that means the $firstname field must have content. If I have a larger form and want to ensure every form field is filled in, is there a PHP function where I can select all form fields with a "name" attribute (or something similar)? I appreciate I could write out the if statement x number of times for each field but I was thinking there must be an inbuilt PHP function for this? But I couldn't see anything in the PHP docs?

Any help would be wonderful.

<?php include "db.php"; ?>

<?php 

if (isset($_POST['submit'])) {

    $firstname = $_POST['first-name'];
    $email = $_POST['email'];

    if ($firstname == "" || empty($firstname)) {

        echo "This field should not be empty";

    } else {

        $query = "INSERT INTO user(firstname, email) VALUE('{$firstname}', '{$email}')";

        $add_name_query = mysqli_query($connection, $query);

        if (!$add_name_query) {

            die('QUERY FAILED' . mysqli_error($connection));

        }

    }

}


?>
pjk_ok
  • 618
  • 7
  • 35
  • 90
  • It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Apr 06 '21 at 23:06
  • Hi @dharman - yes I know, this is just simplified localhost code I'm playing around with I wouldn't use this in production. – pjk_ok Apr 06 '21 at 23:14
  • 1
    Ok, then why are you asking us about it. Please fix this issue first and then look at other issues. There is no point in working anymore with this version of the code. You will have to delete is as soon as you fix it and then write it properly. – Dharman Apr 06 '21 at 23:15
  • 1
    The answer to your question is: No, there is no such thing. PHP has absolutely no idea about your HTML form. PHP can only check what was submitted. It is your responsibility to check whether the values submitted are the ones you expected. – Dharman Apr 06 '21 at 23:23
  • @dharman So if I have 10 form elements I would have to write 10 if statements? – pjk_ok Apr 06 '21 at 23:42
  • 1
    Yes, that is pretty much how it all works. Generally, we would have functions or classes that abstract this from us so it is not a huge issue. – Dharman Apr 06 '21 at 23:43
  • **WARNING**: Writing an access control layer is not easy and there are many opportunities to get it severely wrong. Any modern [development framework](https://www.cloudways.com/blog/best-php-frameworks/) like [Laravel](http://laravel.com/) comes with an [authentication system](https://laravel.com/docs/master/authentication) built-in. At the absolute least follow [recommended security best practices](http://www.phptherightway.com/#security) and **never store passwords as plain-text** or a weak hash like **SHA1 or MD5**. – tadman Apr 07 '21 at 00:15
  • If you're just getting started with PHP and want to build applications, I'd strongly recommend looking at various [development frameworks](https://www.cloudways.com/blog/best-php-frameworks/) to see if you can find one that fits your style and needs. They come in various flavors from lightweight like [Fat-Free Framework](https://fatfreeframework.com/) to far more comprehensive like [Laravel](https://laravel.com/). These give you concrete examples to work from and guidance on how to write your code and organize your project's files. Form handling is a solved problem. – tadman Apr 07 '21 at 00:16
  • What you're talking about here is generally termed "model validations" and is something you effectively get for free in any framework. Here's an example of how [Laravel handles validations](https://laravel.com/docs/8.x/validation) which is very comprehensive and, notably, *very non-trivial to re-implement yourself*. – tadman Apr 07 '21 at 00:17

2 Answers2

2

You could build your own function to make it a little more "dry".

    <?php
    
      $firstname = $_POST['first-name'];
      $email = $_POST['email'];
      $anotherField = "Something";
      $andOneMoreField = "Nothing";
    
      function checkInputField($inputField) {
        if($inputField == "" || empty($inputField)) {
          echo 'This field should not be empty';
          return false;
        } else {
          return true;
        }
      };
    
      if(
        checkInputField($firstname) &&
        checkInputField($email) &&
        checkInputField($anotherField) &&
        checkInputField($andOneMoreField)
        // and so on...
      ) {
        echo "Open doors for SQL-Injection";
        // db-handling
      }
    
    ?>

But this is only as food for thought for further learning. This is neither nice code nor a recommendation for implementation.

2Bias
  • 51
  • 8
  • This is a good sketch of the overall concept, but you're right, this is a long way off of what you should actually use in production. – tadman Apr 07 '21 at 00:15
1

Another way to do the same:

<?php
function isEmptyField($value) {
    return (trim($value) == "" || empty($value)) ? true : false;
}

$fieldNames = array('first-name', 'email'); //You can add others fields name here.
$fieldsOk = true;

foreach($fieldNames as $fieldName) {
    if(! array_key_exists($fieldName, $_POST) || isEmptyField($_POST[$fieldName])) {
        echo "The field {$fieldName} should not be empty! \r\n";
        $fieldsOk = false;
        //break; //You could break the validation if a field is empty.
    }
}

if($fieldsOk) {
    //TODO: INSERT QUERY!
}
?>

But I think you will need others validations for each field according to their data types.

nachospiu
  • 2,009
  • 2
  • 8
  • 12