Jump to content

forms forms forms... Please help


Kylemcc

Recommended Posts

Good Day.

I have taken on a project of creating a booking sheet for my colleagues.

we are based in the volunteer security field, i have bought a domain and started setting it up.

my idea is to have the member login to the site and be able to book his hours on completion of his shift and then for the site to export the data for a selected user to a predefined php spreadsheet.

for now i am not worried about the login features, i would just like to get it up and running so that the member can go on to the site and fill out the form and from there, the site will save all the data to a mysql database that i have built.

at the moment i will just be distinguishing between the members by their staff number as this is unique for each member.

i am having a few issues though as i am fairly new to php.

I know it is not pretty but i will be formatting the webpage with headers after i can get this going

please see attached code.

<html>
<?php require_once('connection.php'); ?>
	<head>
	</head>
		<body>
		<form action="bookdata.php" method="post">
		<!--Required-->Staff Number: <input type="number" name="staffnumber"><br /> <!--this would be an 8 digit number that would then distinguish between the different members-->
		<!--Required-->Start Date: <input type="date" name="datestart"><br /> <!--this is the date when the shift started-->
		<!--Required-->Start Time: <input type="time" name="timestart"> <!--This is the time started-->
		<!--Required-->Start OB: <input type="number" name="obstart"><br /> <!--this is the referance number from the control centre that you have started shift--> 
		<!--Required-->End Date: <input type="date" name="dateend"><br /> <!--this is the date when the shift finished, shift might go overnight-->
		<!--Required-->End Time: <input type="time" name="timeend"> <!--This is the time started, shift might go overnight into the next morning-->
		<!--Required-->End OB: <input type="text" name="obend"><br /> <!--this is the referance number from the control centre that you have finished shift-->
		Total Hours: <input type="text" name="hours"> <!--this would be an outomatic calculation and i do not want the member to be able to type into this field-->
		Number of 56 notices: <input type="number" name="no56"><br /> <!--this is a simple number-->
		Number of 341 notices: <input type="number" name="no341"><br /> <!--this is a simple number-->
		Number of hotspots checked: <input type="number" name="nohotspots"><br /> <!--this is a simple number-->
		Number of arrests: <input type="number" name="noarrests"><br /> <!--this is a simple number-->
		Name of accused: <input type="text" name="nameofaccused"><br /> <!--this would be a field with one name or multiple names in it-->
		CAS of arrest: <input type="text" name="arrestcas"><br /> <!--the member must be able to type numbers that will concatenate with the month and year. eg: 1234/06/2018-->
		SAPS arrest location: <input type="text" name="arreststation"><br /> <!--i would like this field to be a drop down list with about 7 options-->
		<input type="submit" name="submit">
		<input type="button" onclick="alert('Hello World!')" value="Click Me!">
		</form>
		
		
			<?php
			
			if(isset($_POST['submit'])){
			
			$sql = "INSERT INTO Bookings (staffnumber,datestart,obstart,dateend,obend,no56,no341,nohotspots,noarrests,nameofaccused,arrestcas,arreststation) Values ('$_POST[staffnumber]','$_POST[datestart]','$_POST[obstart]','$_POST[dateend]','$_POST[obend]','$_POST[no56]','$_POST[no341]','$_POST[nohotspots]','$_POST[noarrests]','$_POST[nameofaccused]','$_POST[arrestcas]','$_POST[arreststation]')";
			
			mysql_query($sql);
			}
			?>
		</body>
</html>

any assistance would greatly be appreciated.

thank you 

Kyle

Link to comment
Share on other sites

Put the processing of the post data before the form output. That way you can validate and redisplay if there are error messages.

Input fields can be given a "required" attribute but still check in the php in case their browser doesn't support the attribute.

Do not store lists of items in a single field. Each item should be stored in its own record in a separate table (linked to the original record via a foreign key). Have your form allow for multiple arrest inputs. Number of arrests would be unneccesary, the number of associated arrest records would give you that.

"SAPS arrest loacation" would be a "select" input field (dropdown) and not a text input. You would build the option list for the select from a separate table.

+---------------+
|   staff       |
+---------------+
| staffnumber   |---+
| firstname     |   |
| lastname      |   |    +--------------------+
+---------------+   |    |  booking           |                                                 +-----------------+
                    |    +--------------------+                                                 |  saps_location  |
                    |    |  booking_id        |------+                                          +-----------------+
                    +---<|  staffnumber       |      |                                  +-------| saps_id         |
                         |  datestart         |      |        +-----------------+       |       | locationname    |
                         |  obstart           |      |        | arrest          |       |       +-----------------+
                         |  dateend           |      |        +-----------------+       |
                         |  obend             |      |        | arrest_id       |       |
                         |  no56              |      +-------<| booking_id      |       |
                         |  no341             |               | nameofaccused   |       |
                         |  nohotspots        |               | arrestcas       |       |
                         +--------------------+               | saps_id         |>------+
                                                              +-----------------+

EDIT:

Nearly forgot - don't put post values (or any other user input) directly into the query. Use prepared statements and pass the values as parameters. To do this, forget about mysql_* functions. The rest of the world has. Change to the PDO function library for your database processing.

PS Do not use "submit" as an input name. Having a form item named "submit" interferes with the form's "submit" method

Link to comment
Share on other sites

Barand gave a lot of good advice and there is a lot more that can/should be done. However, a forum post is not the right medium to give a tutorial on all the aspects in creating a good form. But, I will elaborate on one thing Barand stated:

On 6/3/2018 at 6:39 AM, Barand said:

Put the processing of the post data before the form output. That way you can validate and redisplay if there are error messages.

Right now, three is no "processing logic", there is just a single statement to INSERT the data into the DB. As Barand stated you need to be using "prepared statements" (here's a good tutorial). But, you need to validate the user input before you even attempt to INSERT the data, otherwise simple input mistakes will  lead to corrupt data. For example,  you need to check that required fields have an input and for any fields that do have an input you need to ensure it is a proper value for that field. Number fields should be numbers, dates should be dates, etc. Also, if a field has a properly formatted value, it may still not be valid. You wouldn't want to accept a date if the user accidentally entered a year of 2118, right? One way to help users enter data (especially when format is important, i.e. date) is to use the placeholder parameter for input fields. It puts an "example" value as a guid into the field until the user puts focus on the field

<input type="text" name="date" placeholder="MM-DD-YYYY">

Also, using javascript plugins for things like date inputs is also a good idea. But, don't rely upon them for ensuring user input is correct. Get the firm working first with just HTML - then add any JavaScript to enhance the user experience.

Here is a quick and dirty example of a form and how I tend to approach them.

<?php
	//Variable to hold form error description
$errorDsc = "";
	//Get the form values (if posted)
$name   = isset($_POST['name'])   ? trim($_POST['name'])     : ''; //Trim strings
$dab    = isset($_POST['dab'])    ? trim($_POST['dab'])      : ''; //Trim strings
$pounds = isset($_POST['pounds']) ? intval($_POST['pounds']) : ''; //Convert to number
	//Check if form was posted
if($_SERVER['REQUEST_METHOD']=="POST")
{
    //Create an array to hold errors
    $errors = array();
    
    //Check name
    if($name=="")
    {
        $errors[] = "Name is required";
    }
    //Check DOB
    if($dab=="")
    {
        $errors[] = "Date of birth is required";
    }
    else
    {
        //Create a timestamp of DOB
        $dabTS = strtotime($dab);
        //Check if DOB was invalid or in the future
        if(!$dabTS or $dabTS>time())
        {
            $errors[] = "Date of birth must be validly formatted (mm-dd-yyyy) and not in the future.";
        }
    }
    //Check weight - 0 will be value if no input provided because of intval() above
    if($pounds<0)
    {
        $errors[] = "Weight cannot be negative.";
    }
	    //Check if there were errors
    if(!count($errors))
    {
        //Prepare the error description
        $errorDsc = "Please correct the following errors:<br><ul>\n";
        foreach($errors as $err)
        {
            $errorDsc .= "<li>{$err}</li>\n";
        }
        $errorDsc .= "</ul>\n";
    }
    else
    {
        //Form was posted and all input is valid
        //
        //Create and run prepared statement to insert data into DB
        //Then perform a header redirect to a confirmation page
        //The redirect will prevent a duplicate submission if the
        // user was to click the refresh button
    }
    
}
	
?>
<html>
<head></head>
<body>
	<?php
    //Show the error description
    //Will be empty if form was not posted
    echo $errorDsc;
    //Note, if there were errors, the entered values will be repopulated in 
    //input fields below. select/radio/etc type fields would need a different process
?>
	<form method="post" action="">
    Name:
    <input type="text" name="name" placeholder="" required value="<?php echo htmlentities($name); ?>">
    <br>
    Date of Birth:
    <input type="text" name="dob" placeholder="mm-dd-yyyy" required value="<?php echo htmlentities($dob); ?>">
    <br>
    Weight in pounds:
    <input type="text" name="pounds" placeholder="No. of pounds" value="<?php echo htmlentities($pounds); ?>">
</form>
	</body>
</html>

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.