PHP newb need help with guestbook assignment.


#1

Hello,

I’m following a course in PHP and they’ve given me an assignment to write a guestbook, but I’m a bit stuck.
The assignment is:
Make a guestbook for sport fans and practitioners.
Show an error message if they haven’t filled in every field and tell them which field to fill in.
The field practitioner should only contain true of false
The field sport should contain: tennis, boxing, running, squash, cycling and tabletennis and should be displayed through a select box. (as in html select)
Using a table in a database:
ID (INT, AUTO_INCREMENT, PRIMARY KEY, NOT NULL)
Naam (50 karakters, NOT NULL) // English: Name
Boodschap (TEKST, NOT NULL) // English: Message
Datum (datetime) // English: Date
Sport (30 karakters)
Beoefenaar (BOOLEAN, default FALSE) // English: Practitioner
Now the real problem is that I don’t know how I can get php to display my sport array as a select field…
The things I have so far (the variables are in Dutch but sport is still sport :slight_smile: ) :

<?php /* connect */ include "connection.php" ; $conn = mysqli_connect($hostname, $username, $password); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } if (!mysqli_select_db($conn ,$database)) { die ("Db niet gevonden"); } /* Houdt ingevulde info bij */ if (isset($_POST['submit']) && $_POST['submit'] == 'Submit'){ if (!isset($_POST['Naam']) || $_POST['Naam']==" "){ echo 'Hebt u uw naam wel ingevuld?'; } elseif (!isset($_POST['Boodschap']) || $_POST['Boodschap']==" "){ echo 'Hebt u uw bericht wel ingevuld?'; } elseif (!isset($_POST['Sport']) || $_POST['Sport']==" "){ echo 'Hebt u uw sport wel gekozen?'; } else { /* Insert info in tabel */ $as_naam= mysqli_real_escape_string ($_POST['Naam']); $as_boodschap= mysqli_real_escape_string ($_POST['Boodschap']); $as_sport= mysqli_real_escape_string ($_POST['Sport']); $query= "INSERT INTO gastenboektabel (Naam, Boodschap, Beoefenaar) VALUES ($as_naam, $as_boodschap)"; } } $sport = array('tennis', 'voetbal', 'running', 'tafeltennis', 'squash', 'wielrennen', 'boksen'); foreach ($sport as $key => $var) $dezepagina= "051R4Invoerenverwerking.php"; $form= <<< EOFORM 051R4

Welkom op het Sportgastenboek!

Bent u een beoefenaar van de sport?
Ja
Nee

Naam:

Sport:

Boodschap:

Bedankt voor uw medewerking!

EOFORM; echo $form; ?>

Thx in advance!


#2

Hi,

as long as i understood your problem:
echo the following https://www.w3schools.com/tags/tag_select.asp


#3

You should only use php code for the parts of your web page that are ‘dynamic’. Static parts should NOT be produced using php code. The html document should be treated as a ‘template’ and be at the end of your file. The dynamic parts that are being produced by php code should come before the start of the html document. The result from the php code should be stored in appropriately named php variable(s). The contents of the php variable(s) should be echoed at the appropriate places in the html document. Doing this will separate the different ‘concerns’ in your code, making it easier to design, write, test, and debug your code.

Now the real problem is that I don't know how I can get php to display my sport array as a select field...

You can research on the web what the html for a select/option menu is. The only part that would be dynamic and would be produced by php code using a loop, would be the choices. If after determining what the html you are trying to produce should be and making an attempt at the code to produce that html, if you cannot solve this problem, post just the relevant part of the code and what errors or symptoms are you getting from that code, and someone will try to help.

Now, if you are doing this as part of a course, there are bunch of unnecessary and bad practices in the code. The following list will actually reduce the amount of code, which again will make it easier to design, write, test, and debug your code.

  1. You can specify the database when you make the connection. This will eliminate several statements from your code.

  2. Don’t unconditionally output database statement (connection, query) errors on a web page. When you are learning, developing, and debugging code, you should display errors. When on a live/public server, you should log errors. The simplest way of doing this is to use exceptions for the database statement errors and let php catch the exception, where it will use its error_reporting, display_errors, and log_errors settings to control what happens with the actual error information. This will let you eliminate the existing database statement error handling logic in your code and give you error handling for the INSERT query, which you aren’t even executing. To enable exceptions for the mysqli extension, add the following line of code before the point where you are making the database connection -
    [php]mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);[/php]

To make this work on your development system, set php’s error_reporting E_ALL (it should always be this value) and set display_errors to ON, preferably in the php.ini. Stop and start your web server to get any changes made to the php.ini to take effect.

  1. Use an array to hold validation error messages. The array then becomes an error flag. If the array is empty, there are no errors. This will simplify the nested logic in your code and let you validate all the inputs at one time. After the validation logic, just test if the array is empty to determine if you should run the INSERT query. To display the validation errors, just test and display the contents of the array at the appropriate place in the html document (you are current echoing the validation errors before the start of the html document and are only validating later inputs if there are no validation errors from earlier inputs.)

  2. When validating the inputs, you would also need to validate that each ‘Sport’ choice is valid. You would use in_array() against your $sport array to do so, and if someone can select multiple choices, the choices should be stored in a separate database table from the primary information, related back to the primary information through the primary’s id (auto-increment integer column.)

  3. Your form processing code should JUST detect that a post method form has been submitted, by testing if $_SERVER[‘REQUEST_METHOD’] == ‘POST’ Besides simplifying the logic, this will insure that the form submission will be detected if you don’t submit the form by clicking on the submit button.

  4. Only un-checked radio and check-box form fields will be unset. This is the only place you should use isset(). All other form fields will be set after the form has been submitted. Using isset() for these, just clutters up your code and hides mistakes between the form fields and your php code.

  5. You are testing if the inputs are a string consisting of a space " ". This is incorrect. You should be testing if they are an empty string “”. Also, the radio field won’t ever be an empty string (unless you use an empty string for one of the values) and the validation you use for the radio field should be to test if it is one of the permitted values.

  6. When you build the choices for the Sport field, the first choice should use an empty string “” for the value (so that you can detect if no choice was made) be a prompt to select the choice(s).

  7. Because the Sport field is being defined as an array and with the MULTIPLE keyword, the submitted data will be an array. You must loop over the data to reference each submitted value.

  8. Use a prepared query when supplying data values to an sql statement. This will both simplify your code/query and prevent sql injection (if the character set that php is using isn’t the same your database tables, sql injection is still possible when using any of the …_escape_string() functions.)

To convert a query to a prepared query, simply -

a) Remove any php variables, concatenation dots, and single-quotes from around the values and replace each with a ? place-holder. Remove any _escape_string() statements.

b) Call the ->prepare() method.

c) For the mysqli extension, you must bind the input variables that were removed in step #1 (if you instead switch to use the much simpler php PDO extension, you can skip this step and just supply the variables as an array in the next step.)

d) Call the ->execute() method.

  1. I notice that you are outputting the before the tag. You will want to validate the html that your page produces at validator.w3.org to insure that it is valid.