/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] On a PHP form, generate a drop-down list based on a text file

New to PHP and trying to set up a course registration form using only PHP and text files, no JavaScript or MySQL. I’ve completed a few HTML contact forms with the associated PHP files but I can’t push the HTML out of my head to move forward with this.

I have index1.php set up and was hoping to paste a .jpg of it. When I call it up on the localhost it displays fine with an input box for Student Name and an input box for Student Number. At this time I have the course options in the HTML body.

[COLOR=”#FF0000″][B]My question: How can I change this to PHP to pull from a text file I’ve created with the course name and course code? Can this also be done using radio buttons?[/B][/COLOR]

[COLOR=”#0000FF”]index1.php code below:[/COLOR]

[CODE]<?php

?>

<html>
<head>
<title>Registration Form</title>
<style>
body{background-color: #ffffe6; width:610px;}
h1 {color: #29a3a3;}
.inputbox {padding: 7px; border: #F0F0F0 2px solid; border-radius: 4px;}
.btn {padding: 10px;background-color: #29a3a3; border: solid thin #000000; color: #FFF; font-weight: bolder; cursor: pointer;}
</style>
</head>

<body>
<h1>Course Registration</h1>
<form name=”regfrm” method=”post” action=””>

<fieldset><legend><strong>Student Information</strong></legend>
<dl>
<dt>Student Name:</dt>
<dd><input class=”inputbox” name=”studentname” type=”text” id=”studentname” required autofocus placeholder=”Please enter your first and last name” tabindex=”10″ size=”50″></dd>
<br>
<br>
<dt for=”number”>Student Number:</dt>
<dd><input class=”inputbox” name=”studentnumber” type=”text” required id=”studentnumber” placeholder=”Please enter using the following format: PX-03-046″ tabindex=”20″ size=”50″></dd>
</dl>
<br>
</fieldset>
<br>
<fieldset><legend><strong>Available Courses</strong></legend>
<p>Please select the course you want to enrol in (select one):
<br>
<label>
<input name=”course” type=”radio” value=”afd” id=”course_0″ tabindex=”30″ >
Animation Film Design:AFD-250</label>
<br>
<label>
<input name=”course” type=”radio” value=”ds” id=”course_1″>
Digital Sculpture:DS-410</label>
<br>
<label>
<input name=”course” type=”radio” value=”ha” id=”course_2″>
History of Animation:HA-240</label>
<br>
<label>
<input name=”course” type=”radio” value=”ve” id=”course_3″>
Visual Effects:VE-298</label>
<br>
</p>
</fieldset>

<div>
<p>
<input name=”reset” type=”reset” tabindex=”40″ value=”Clear Form” class=”btn”>
<input name=”submit” type=”submit” tabindex=”50″ value=”Submit Form” class=”btn”>
</p>
</div>

</form>

</body>
</html>[/CODE]

Thank you!

to post a comment
PHP

35 Comments(s)

Copy linkTweet thisAlerts:
@ginerjmMar 06.2016 — YOu have your html set up in a php file that has no php code in it. What are you asking us to tell you?
Copy linkTweet thisAlerts:
@BlondieCauthorMar 06.2016 — I'm not sure where to start with the PHP. I know I need to include sanitization and validation but the main piece where I am stumped is how to do the drop down list in PHP to pull the data I have in a text file. I have the following text files:

~ Courses: contains the course name and course code and max enrolment number ie Animation Film Design:AFD-250:6

~ Student: contains the student name and student id ieRiley Anderson?X-06-009

~ Enrolment: will contain the student name and student id and selected course and course code upon completion of the form
Copy linkTweet thisAlerts:
@ginerjmMar 06.2016 — You open the file and begin a loop that reads thru each record and generates the html for the radio button for that record's value.

Pseudo code:

$html = ''; // init the var to be displayed

while (get next row)

{

(explode the row into fields - are they comma-separated?)

$html .= "<input type='radio' name='course' value='$course_name'> " . $course_name;

}

Now replace the radio button html code that you had with the $html var where you want the buttons to show.

That's how to do one item.
Copy linkTweet thisAlerts:
@NogDogMar 06.2016 — If I were going to store the form data in a separate text file (as opposed to, perhaps, a database), I'd probably format it as JSON. Then you could simply read the file in and apply PHP json_decode() function to it:
[code=php]
$data = json_decode(file_get_contents('name_of_file.json'), true);
[/code]

At that point, $data in this example is an array you can loop through via foreach() to do whatever you want with it.
Copy linkTweet thisAlerts:
@BlondieCauthorMar 06.2016 — I received an error message when attempting to do what Gingerjim suggested: [COLOR="#0000CD"]Parse error: syntax error, unexpected '{', expecting ',[/COLOR] - I did something wrong at my end.

I continued to work on it after my initial post and came up with code that is almost working (posted below but no option for code tags this time).


~ Take the courses.txt file and convert it to a comma delimited file as coursesfinal.txt. Field 0 is Course Name, Field 1 is Course Code, Field 2 is max of number of people who can enrol.

~ The drop down list now displays, but it's displaying the course code only and not the course name followed by the course code.
Copy linkTweet thisAlerts:
@ginerjmMar 06.2016 — If you have code that is being problematic, Post It so we can see.
Copy linkTweet thisAlerts:
@BlondieCauthorMar 06.2016 — It would help if I posted it.

<?php

// Convert courses.txt file to comma delimited file coursesfinal.txt

$in = "courses.txt";

$out = "coursesfinal.txt";

$IN = fopen ($in, 'r') or die ("$in cannot be opened for reading.");

$OUT = fopen ($out, 'w') or die ("$out cannot be opened for writing.");

if (flock($OUT, LOCK_EX)) {

while ($inline = fgets ($IN) ) {

$splitarray = explode (":", $inline);

$outline = implode(",", $splitarray);

fputs ($OUT, $outline);

}

flock($OUT, LOCK_UN);

}

fclose ($IN);

fclose ($OUT);

// Search coursesfinal.txt file for course to match user input

$datafile = "coursesfinal.txt";

// If selection has been made, find a match

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

$course = htmlentities ($_
POST['']);

$DB = fopen ($datafile, 'r') or die ("$datafile cannot be opened for reading.");

$found = FALSE;
while ($record = fgets ($DB) and ! $found) {
$field = explode (",", htmlentities (trim ($record)));
$found = $course ==+ $field[0];
}

fclose ($DB);

if ($found) {
echo "<p>You have selected: $field[0] $field[1]</p>n";
}

}


?>


<html>

<head>

<title>Registration Form</title>

<style>

body{background-color: #ffffe6; width:610px;}

h1 {color: #29a3a3;}

.inputbox {padding: 7px; border: #F0F0F0 2px solid; border-radius: 4px;}

.btn {padding: 10px;background-color: #29a3a3; border: solid thin #000000; color: #FFF; font-weight: bolder; cursor: pointer;}

</style>

</head>

<body>

<h1>Course Registration</h1>

<form name="regfrm" method="post" action="">

<fieldset><legend><strong>Student Information</strong></legend>
<dl>
<dt>Student Name:</dt>
<dd><input class="inputbox" name="studentname" type="text" id="studentname" required autofocus placeholder="Please enter your first and last name" tabindex="10" size="50"></dd>
<br>
<br>
<dt for="number">Student Number:</dt>
<dd><input class="inputbox" name="studentnumber" type="text" required id="studentnumber" placeholder="Please enter using the following format: PX-03-046" tabindex="20" size="50"></dd>
</dl>
<br>
</fieldset>
<br>

<fieldset><legend><strong>Available Courses</strong></legend>
<br>


<?php

// Generate the form

echo " Select a Course: <select name="course">n";

$DB = fopen ($datafile, 'r') or die ("$datafile cannot be opened for reading.");
while ($record = fgets ($DB) ) {
$field = explode (",", htmlentities (trim ($record)));
echo " <option value="$field[0]">$field[1]</option>n";

}

fclose ($D?;

echo " </select>n";

?>

<br>

<br>

<br>

<br>

<br>

<br>


</fieldset>

<div>
<p>
<input name="reset" type="reset" tabindex="40" value="Clear Form" class="btn">
<input name="submit" type="submit" tabindex="50" value="Submit Form" class="btn">
</p>
</div>


</form>

</body>

</html>
Copy linkTweet thisAlerts:
@ginerjmMar 06.2016 — 1 - please wrap your code sample in the proper tags: php and php in square brackets.

2 - Since you seem to already have the course data in your own file, why don't you just clean the data ONCE before ever using it in this script and avoid having to use functions on the data when you use it later every time?

3 - You don't have to convert the input file to comma separated. If it is delineated by colons already then just explode it using a : as the delimiter.

4 - You said you had an error but now that you posted all that code why did you not point out the line with the error?
Copy linkTweet thisAlerts:
@BlondieCauthorMar 06.2016 — 1 - There wasn't a code tag option on the tool bar so I was't able to wrap my code and I wasn't aware I could do it with square brackets - thanks for the tip. So just...

[

all of my code in here?

]

2 - I need the course file for additional testing that will take place.

3 - It is delineated by colons Animation Film Design:AFD-250:6. I didn't realize it didn't have to be converted first.

4 - The code I posted is not the code with the error. It's the code I was able to make some headway with.
Copy linkTweet thisAlerts:
@rootMar 06.2016 — as for the form... you need to set the enctype for the form if you are POSTing your form.

This bit I would do a bit differently
[code=php]<?php
// Generate the form
echo " Select a Course: <select name="course">n";

$DB = fopen ($datafile, 'r') or die ("$datafile cannot be opened for reading.");
while ($record = fgets ($DB) ) {
$field = explode (",", htmlentities (trim ($record)));
echo " <option value="$field[0]">$field[1]</option>n";
}
fclose ($DB);

echo " </select>n";

?> [/code]


I would do it more like.
[code=php]Select a Course: <select name="course">
<option value="-1" selected>Please Select...</option>
<?php
// Get the data
$DB = fopen ($datafile, 'r') or die ("$datafile cannot be opened for reading.");
// I will assume this bit works after the change...
while ( !feof($DB) ) {

// use a CSV function to pull the information rather than explode.
$field = fgetcsv($DB);

// use sprintf formatting to make complex output simpler, use PHP_EOL for end of line
echo sprintf(" <option value='%s'>%s</option>%s", $field[0], $field[1], PHP_EOL );
}
fclose ($DB);
?>
</select>
[/code]


It would be much better if you use a database like MySQL if you can't use MySQL for whatever reason, porting your data file in to an SQLite3 database, means you can simply get the advantages of a database within your script and use SQL type queries, easily update, etc.
Copy linkTweet thisAlerts:
@BlondieCauthorMar 07.2016 — I recognize you. You helped me ages ago with JavaScript.

The second line in your code - I was wondering how to do that - thanks. I ran what you provided and only the course codes appear in the drop down list. If I understand your code correctly this should display the course name and the course code? [code=php]echo sprintf(" <option value='%s'>%s</option>%s", $field[0], $field[1], PHP_EOL );[/code]

[code=php]<?php
// Convert courses.txt file to comma delimited file coursesfinal.txt
$in = "courses.txt";
$out = "coursesfinal.txt";

$IN = fopen ($in, 'r') or die ("$in cannot be opened for reading.");
$OUT = fopen ($out, 'w') or die ("$out cannot be opened for writing.");

if (flock($OUT, LOCK_EX)) {
while ($inline = fgets ($IN) ) {
$splitarray = explode (":", $inline);
$outline = implode(",", $splitarray);
fputs ($OUT, $outline);
}
flock($OUT, LOCK_UN);
}

fclose ($IN);
fclose ($OUT);

// Search coursesfinal.txt file for course to match user input
$datafile = "coursesfinal.txt";

// If selection has been made, find a match
if (isset ($_POST['course'])) {
$course = htmlentities ($_POST['']);
$DB = fopen ($datafile, 'r') or die ("$datafile cannot be opened for reading.");

$found = FALSE;
while ($record = fgets ($DB) and ! $found) {
$field = explode (",", htmlentities (trim ($record)));
$found = $course === $field[0];
}

fclose ($DB);

if ($found) {
echo "<p>You have selected: $field[0] $field[1]</p>n";
}
}


?>


<html>
<head>
<title>Registration Form</title>
<style>
body{background-color: #ffffe6; width:610px;}
h1 {color: #29a3a3;}
.inputbox {padding: 7px; border: #F0F0F0 2px solid; border-radius: 4px;}
.btn {padding: 10px;background-color: #29a3a3; border: solid thin #000000; color: #FFF; font-weight: bolder; cursor: pointer;}
</style>
</head>

<body>
<h1>Course Registration</h1>
<form name="regfrm" method="post" action="">

<fieldset><legend><strong>Student Information</strong></legend>
<dl>
<dt>Student Name:</dt>
<dd><input class="inputbox" name="studentname" type="text" id="studentname" required autofocus placeholder="Please enter your first and last name" tabindex="10" size="50"></dd>
<br>
<br>
<dt for="number">Student Number:</dt>
<dd><input class="inputbox" name="studentnumber" type="text" required id="studentnumber" placeholder="Please enter using the following format: PX-03-046" tabindex="20" size="50"></dd>
</dl>
<br>
</fieldset>
<br>

<fieldset><legend><strong>Available Courses</strong></legend>
<br>


Select a Course: <select name="course">
<option value="-1" selected>Select From...</option>
<?php
// Get the data
$DB = fopen ($datafile, 'r') or die ("$datafile cannot be opened for reading.");
// I will assume this bit works after the change...
while ( !feof($DB) ) {

// use a CSV function to pull the information rather than explode.
$field = fgetcsv($DB);

// use sprintf formatting to make complex output simpler, use PHP_EOL for end of line
echo sprintf("<option value='%s'>%s</option>%s", $field[0], $field[1], PHP_EOL );
}
fclose ($DB);
?>
</select>




<br>
<br>
<br>
<br>
<br>
<br>
<br>
</fieldset>

<div>
<p>
<input name="reset" type="reset" tabindex="40" value="Clear Form" class="btn">
<input name="submit" type="submit" tabindex="50" value="Submit Form" class="btn">
</p>
</div>

</form>

</body>
</html>[/code]
Copy linkTweet thisAlerts:
@BlondieCauthorMar 07.2016 — as for the form... you need to set the enctype for the form if you are POSTing your form.

This bit I would do a bit differently
[code=php]<?php
// Generate the form
echo " Select a Course: <select name="course">n";

$DB = fopen ($datafile, 'r') or die ("$datafile cannot be opened for reading.");
while ($record = fgets ($DB) ) {
$field = explode (",", htmlentities (trim ($record)));
echo " <option value="$field[0]">$field[1]</option>n";
}
fclose ($DB);

echo " </select>n";

?> [/code]


I would do it more like.
[code=php]Select a Course: <select name="course">
<option value="-1" selected>Please Select...</option>
<?php
// Get the data
$DB = fopen ($datafile, 'r') or die ("$datafile cannot be opened for reading.");
// I will assume this bit works after the change...
while ( !feof($DB) ) {

// use a CSV function to pull the information rather than explode.
$field = fgetcsv($DB);

// use sprintf formatting to make complex output simpler, use PHP_EOL for end of line
echo sprintf(" <option value='%s'>%s</option>%s", $field[0], $field[1], PHP_EOL );
}
fclose ($DB);
?>
</select>
[/code]


It would be much better if you use a database like MySQL if you can't use MySQL for whatever reason, porting your data file in to an SQLite3 database, means you can simply get the advantages of a database within your script and use SQL type queries, easily update, etc.[/QUOTE]


Forgot to include... I will be learning MySQL shortly but for now have to use text files.
Copy linkTweet thisAlerts:
@rootMar 07.2016 — Hi,

Possibly, your name seems familiar..

I am assuming that your file you are using is a CSV format file that is terminated in a newline.

You should look at PHP a little closer with regard to pulling data out of a CSV, some functions exist to help cut away at code and slim it down.

MySQL or SQLite3 are much more efficient at dealing with data than a flat file.

I don't want to seem rude but I am going to bed, its 1am and I have to be up at 5am..!
Copy linkTweet thisAlerts:
@BlondieCauthorMar 07.2016 — Holy crap you're going to be tired. It's 8pm here and I'll be going to bed at 9 to get up at 5.

I'll do some more reading and video watching to find out what I can learn.

Thank you.
Copy linkTweet thisAlerts:
@BlondieCauthorMar 07.2016 — Data available for the drop down list is: the course name:Animation Film Design, the course code:AFD-250, and the max number of people that can enrol:6.

At this time the drop down list displays the course code only and I would like it to display the course name first, then the course code.

Thank you.
Copy linkTweet thisAlerts:
@NogDogMar 07.2016 — Just want to point out that these two statements are functionally synonymous, so you might as well use the second:
[code=php]
echo sprintf("stuff goes here");
printf("stuff goes here");
[/code]

?

As far as how I would solve your issue, I don't yet have a clear understanding of what these input files look like (maybe I'm just too tired to glean the necessary information from all the posts here). A nice clean sample of what the text file looks like (within [noparse]...[/noparse] bbcode tags here) followed by a representation of how you want that data output (likely within [noparse][code=html]...[/code][/noparse] tags) would make life a bit simpler for those of us who'd like to help, but have had a long weekend and are inherently lazy on top of that. ?
Copy linkTweet thisAlerts:
@BlondieCauthorMar 07.2016 — The data in the coursesfinal.txt file is as follows - the course name, course code and max number of people that can enrol:
Animation Film Design,AFD-250,6
Digital Sculpture,DS-410,4
History of Animation,HA-240,6
Visual Effects,VE-298,4


Currently when I run localhost/index.php (previosly index1.php), the content displays fine with an input field for the student name, an input field for the student number and the drop down list which displays the course codes AFD-250, DS-410, HA-240, VE-298.

I would like the drop down list to display the course name and course code:

Animation Film Design AFD-250

Digital Sculpture DS-410

History of Animation HA-240

Visual Effects VE-298

Thank you.
Copy linkTweet thisAlerts:
@ginerjmMar 07.2016 — As to how to display something this line works just as well as sprint or printf:

echo "stuff goes here";

As to how to change how your radio buttons show you can do

(the code tag is square brackets surrounding 'php')

[code=php]
echo "<input type='radio' name='course' value='$course_code'> $course_name $course_code<br>";
[/code]

(the closing tag is square brackets surrounding /php)

or however you want to use your content vars.
Copy linkTweet thisAlerts:
@NogDogMar 07.2016 — As to how to display something this line works just as well as sprint or printf:

echo "stuff goes here";
[/QUOTE]


Well...I was assuming they were going to actually use [s]printf() with place-holders and replacement args, just didn't feel like typing them out. :p
Copy linkTweet thisAlerts:
@NogDogMar 07.2016 — [code=php]
$fh = fopen('/path/to/course_file.txt', 'r');
while(($row = fgetcsv($fh)) != false) {
if(count($row == 3) {
printf(
"<input type='radio' name='course' value='%s'>%s %s<br>n",
htmlentities($row[1]),
htmlentities($row[0]),
htmlentities($row[1])
);
}
}
[/code]
Copy linkTweet thisAlerts:
@BlondieCauthorMar 08.2016 — [code=php]
$fh = fopen('/path/to/course_file.txt', 'r');
while(($row = fgetcsv($fh)) != false) {
if(count($row == 3) {
printf(
"<input type='radio' name='course' value='%s'>%s %s<br>n",
htmlentities($row[1]),
htmlentities($row[0]),
htmlentities($row[1])
);
}
}
[/code]
[/QUOTE]


Would this code replace...
[code=php]<?php
// Generate the form
//echo " Select a Course: <select name="course">n";

$DB = fopen ($datafile, 'r') or die ("$datafile cannot be opened for reading.");
while ($record = fgets ($DB) ) {
$field = explode (",", htmlentities (trim ($record)));
echo " <option value="$field[0]">$field[1]</option>n";
}
fclose ($DB);

echo " </select>n";


?>[/code]
Copy linkTweet thisAlerts:
@BlondieCauthorMar 08.2016 — I replace this code
[code=php]<?php
// Generate the form
//echo " Select a Course: <select name="course">n";

$DB = fopen ($datafile, 'r') or die ("$datafile cannot be opened for reading.");
while ($record = fgets ($DB) ) {
$field = explode (",", htmlentities (trim ($record)));
echo " <option value="$field[0]">$field[1]</option>n";
}
fclose ($DB);

echo " </select>n";


?>[/code]


With
[code=php]Select a Course: <select name="course">
<option value="-1" selected>Select From...</option>
<?php
// Generate the form
$DB = fopen ($datafile, 'r') or die ("$datafile cannot be opened for reading.");
while ($record = fgets ($DB) ) {
$field = explode (",", htmlentities (trim ($record)));
echo " <option value="$field[1]">$field[0] $field[1]</option>n";
}
fclose ($DB);

echo " </select>n";

?>[/code]


The drop down list now displays the course name followed by a space followed by the course code.
Copy linkTweet thisAlerts:
@NogDogMar 08.2016 — Would this code replace...
[code=php]<?php
// Generate the form
//echo " Select a Course: <select name="course">n";

$DB = fopen ($datafile, 'r') or die ("$datafile cannot be opened for reading.");
while ($record = fgets ($DB) ) {
$field = explode (",", htmlentities (trim ($record)));
echo " <option value="$field[0]">$field[1]</option>n";
}
fclose ($DB);

echo " </select>n";


?>[/code]
[/QUOTE]

All except for the line where you echo out the closing </select> tag -- and assuming I didn't make any silly mistakes. ?
Copy linkTweet thisAlerts:
@ginerjmMar 08.2016 — One thing in your explode line: The trim function will only trim the spaces from the start and the end of the entire $record string and NOT each quasi-field in that string. If you need to trim each resulting array element you should do that on the array instead of the just-read string.

For Future Reference:

One should really practice separating the presentation code (html) from the logic code (the PHP). Look at your current scriptlet. You start right out by sending out some html. Then you start doing the data retrieval and generation of the output from that data. But wait - what if your file open fails to happen and your code then fails to do anything? You have a hanging dropdown on your client screen. How do you handle that?

Do your php code first so that you know for sure what you will be able to output. In your case open the file and build a php var to contain the output you wish to generate from that process. Continue with your other dropdowns generating new php vars. When you have finishing 'building' your page, THEN start doing your output of the html with these php vars inserted where they belong.

Pseudo code:

(open the first data file and create a var $dropdown1 that will contain the html from <select> to </select>)

(repeat for other dropdowns and create $dropdown1, $dropdown3, etc)

(Output your entire html code with the above $dropdownx vars stuck in the right place to create the output image that you want to see.)
Copy linkTweet thisAlerts:
@BlondieCauthorMar 09.2016 — One thing in your explode line: The trim function will only trim the spaces from the start and the end of the entire $record string and NOT each quasi-field in that string. If you need to trim each resulting array element you should do that on the array instead of the just-read string.

For Future Reference:

One should really practice separating the presentation code (html) from the logic code (the PHP). Look at your current scriptlet. You start right out by sending out some html. Then you start doing the data retrieval and generation of the output from that data. But wait - what if your file open fails to happen and your code then fails to do anything? You have a hanging dropdown on your client screen. How do you handle that?

Do your php code first so that you know for sure what you will be able to output. In your case open the file and build a php var to contain the output you wish to generate from that process. Continue with your other dropdowns generating new php vars. When you have finishing 'building' your page, THEN start doing your output of the html with these php vars inserted where they belong.

Pseudo code:

(open the first data file and create a var $dropdown1 that will contain the html from <select> to </select>)

(repeat for other dropdowns and create $dropdown1, $dropdown3, etc)

(Output your entire html code with the above $dropdownx vars stuck in the right place to create the output image that you want to see.)[/QUOTE]


I really appreciate the direction and instruction. It's pretty easy to see this is very new learning for me.

Re your comment about the trim function. To me it makes more sense that I would want to trim each individual piece of data. I looked at this on php.net/manual and found an example using trim() - is it this idea that I would apply?
[code=php]<?php
function trim_value(&$value)
{
$value = trim($value);
}

$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);

array_walk($fruit, 'trim_value');
var_dump($fruit);

?>[/code]


Re your Future Reference very helpful tips. I had a feeling I shouldn't be mixing my HTML and PHP they way I was and that all the HTML should be together and all the PHP should be together. I will only have three user fields: an input box for their name, and input box for their student ID and the drop down list for them to select a course.

So opening the file is first, then the php var for each of those three user related items?

Those who help on here must have the patience of a Saint but those of us trying to learn - me, really appreciate it and the additional information and tips to do things the right way. Thank you.
Copy linkTweet thisAlerts:
@ginerjmMar 09.2016 — You could just trim each element of $field as you output it.

Separating the types of codes is essential to develop clean, understandable and easily maintainable scripts. One thing that I do is wrap ALL of my html in a function (I call it DisplayPage) which I call after I have finished with my logic. The function contains all of the typical html headers and such as well as the JS code. It's basically the html page that I want to see with the dynamic content replace by a php var. Keeps the html completely out of the way by placing this function at the bottom of my script. Nothing gets output except thru here, except for fatal error messages that go to the screen instead of the normal html

Patience? Most of the time. I have been chastised a couple of times for losing it tho.
Copy linkTweet thisAlerts:
@NogDogMar 09.2016 — And in the spirit of DRY code (Don't Repeat Yourself), you could make a little helper function to safely/cleanly output any variables:
[code=php]
// this should be defined outside of any loops or ifs:
function clean($text, $charset = 'UTF-8')
{
return htmlentities(trim($text), ENT_QUOTES | HTML401, $charset);
}

// usage:
echo ' <option value="'.clean($field[1]).'">'.clean($field[0]).' '.clean($field[1])."</option>n";
// or (in this case easier to read, I think):
printf(
" <option value="%s">%s %s</option>n",
clean($field[1]),
clean($field[0]),
clean($field[1])
);
[/code]
Copy linkTweet thisAlerts:
@BlondieCauthorMar 10.2016 — I started backtracking and removing code and going step-by-step to get things right and clean up the code. Hours later I haven't caught up to the additional code you have both provided but do find myself with another situation. I'm surprised I cannot find a video or example similar to what I am trying to do.

I've set the variables leaving the first three blank as the first two are for input boxes and the third one is the dreaded drop down list but I may be handling this one for the drop down list incorrectly. Do I require a variable for each item in the list?

The reason I ask is now that I moved the output that will be displayed in the list down to the Select a Course fieldset, the drop down list displays the "Available Courses..." but only one course from the four available and it's the fourth one as listed in the coursesfinal.txt file.

In the Student Name and Student Name I've also added the value= code and in doing so, the placeholder text no longer displays - is this to be expected?

Stripped down code:
[code=php]<html>
<head>
<title>Registration Form</title>
<style>
body{background-color: #ffffe6; width:610px;}
h1 {color: #29a3a3;}
.inputbox {padding: 7px; border: #F0F0F0 2px solid; border-radius: 4px;}
.btn {padding: 10px;background-color: #29a3a3; border: solid thin #000000; color: #FFF; font-weight: bolder; cursor: pointer;}
</style>


<?php
// Sanitization and Validation coding will go here





// Initialize and set variables
$studentname = " ";
$studentnumber = " ";
$courses = " ";
$datafile = "coursesfinal.txt";



// Convert courses.txt file to comma delimited file coursesfinal.txt
$in = "courses.txt";
$out = "coursesfinal.txt";
$IN = fopen ($in, 'r') or die ("$in cannot be opened for reading.");
$OUT = fopen ($out, 'w') or die ("$out cannot be opened for writing.");

if (flock($OUT, LOCK_EX)) {
while ($inline = fgets ($IN) ) {
$splitarray = explode (":", $inline);

$outline = implode(",", $splitarray);

fputs ($OUT, $outline);
}
flock($OUT, LOCK_UN);
}

fclose ($IN);
fclose ($OUT);


// Generate the form
$DB = fopen ($datafile, 'r') or die ("$datafile cannot be opened for reading.");
while ($record = fgets ($DB) ) {
$field = explode (",", htmlentities (trim ($record)));
//echo " <option value="$field[1]">$field[0] $field[1]</option>n"; //Moved to the Select a Course fieldset below
}
fclose ($DB);




?>

</head>

<body>
<h1>Course Registration</h1>
<form method="post" action="index.php">

<fieldset><legend><strong>Student Information</strong></legend>
<dl>
<dt>Student Name:</dt>
<dd><input class="inputbox" name="studentname" type="text" id="studentname" value="<?php echo $studentname;?>" required autofocus placeholder="Please enter your first and last name" tabindex="10" size="50"></dd>
<br>
<br>
<dt>Student Number:</dt>
<dd><input class="inputbox" name="studentnumber" type="text" id="studentnumber" value="<?php echo $studentnumber;?>" required placeholder="Please enter using the following format: PX-03-046" tabindex="20" size="50"></dd>
</dl>
<br>
</fieldset>
<br>

<fieldset><legend><strong>Course Selection</strong></legend>
<br>
Select a Course:<select name="courses" tabindex="30">n";
<option value="-1" >Available Courses...</option> <?php echo " <option value="$field[1]">$field[0] $field[1]</option>n"; ?>

</select>

<br>
<br>
<br>
<br>
<br>
<br>
</fieldset>

<div>
<p>
<input name="reset" type="reset" tabindex="40" value="Clear Form" class="btn">
<input name="submit" type="submit" tabindex="50" value="Submit Form" class="btn">
</p>
</div>

</form>

</body>
</html>[/code]
Copy linkTweet thisAlerts:
@NogDogMar 10.2016 — Pardon me if I missed this earlier, but why to you read from the one file and immediately write to another file? Unless I'm missing something (which I may have), you should only need to read the data in from the "in" file. Then the option is to either write the fields into an array (probably an array of arrays in this case), or somewhat simpler (at least in terms of amount of code) is to just read/parse each line as you're ready to use it in the form output.

To that end, you'll need [i]some[/i] kind of loop to set each option in the select element, either a foreach loop on the aforementioned array, or a while loop on the reading of the text file line by line.
Copy linkTweet thisAlerts:
@BlondieCauthorMar 10.2016 — Pardon me if I missed this earlier, but why to you read from the one file and immediately write to another file? Unless I'm missing something (which I may have), you should only need to read the data in from the "in" file. Then the option is to either write the fields into an array (probably an array of arrays in this case), or somewhat simpler (at least in terms of amount of code) is to just read/parse each line as you're ready to use it in the form output.

To that end, you'll need [i]some[/i] kind of loop to set each option in the select element, either a foreach loop on the aforementioned array, or a while loop on the reading of the text file line by line.[/QUOTE]


I doubt you missed something. It's me not having a clue as to how to do this. I know I need a .txt file to store the course name, course code and max enrolment number which would be my "in" file. I thought I needed an "out" file as well to convert the data so it could then be read and used in the drop down list.
Copy linkTweet thisAlerts:
@NogDogMar 10.2016 — Nah, I'd just read it in and use what you get within the script: processing data in RAM is much more efficient than disk I/O.

No guarantees this works, but it's just things rearranged a bit and tightened up to remove superfluous code -- and maybe even work:
[code=php]
<html>
<head>
<title>Registration Form</title>
<style>
body{background-color: #ffffe6; width:610px;}
h1 {color: #29a3a3;}
.inputbox {padding: 7px; border: #F0F0F0 2px solid; border-radius: 4px;}
.btn {padding: 10px;background-color: #29a3a3; border: solid thin #000000; color: #FFF; font-weight: bolder; cursor: pointer;}
</style>
</head>
<body>
<?php
// Sanitization and Validation coding will go here

// Initialize and set variables
$studentname = " ";
$studentnumber = " ";
$courses = " ";
$datafile = "coursesfinal.txt";
$in = fopen ('course.txt', 'r') or die ("courses.txt cannot be opened for reading.");
?>
<h1>Course Registration</h1>
<form method="post" action="index.php">
<fieldset><legend><strong>Student Information</strong></legend>
<dl>
<dt>Student Name:</dt>
<dd><input class="inputbox" name="studentname" type="text" id="studentname" value="<?php echo $studentname;?>" required autofocus placeholder="Please enter your first and last name" tabindex="10" size="50"></dd>
<br>
<br>
<dt>Student Number:</dt>
<dd><input class="inputbox" name="studentnumber" type="text" id="studentnumber" value="<?php echo $studentnumber;?>" required placeholder="Please enter using the following format: PX-03-046" tabindex="20" size="50"></dd>
</dl>
<br>
</fieldset>
<br>
<fieldset><legend><strong>Course Selection</strong></legend>
<br>
Select a Course:<select name="courses" tabindex="30">n";
<option value="-1" >Available Courses...</option>
<?php
while(($field = fgetcsv($in, null, ':')) != false) {
if (count($row) > 1) {
echo "
<option value="$field[1]">$field[0] $field[1]</option>";
}
}
?>
</select>
<br>
<br>
<br>
<br>
<br>
<br>
</fieldset>
<div>
<p>
<input name="reset" type="reset" tabindex="40" value="Clear Form" class="btn">
<input name="submit" type="submit" tabindex="50" value="Submit Form" class="btn">
</p>
</div>
</form>
</body>
</html>
[/code]
Copy linkTweet thisAlerts:
@BlondieCauthorMar 10.2016 — Nah, I'd just read it in and use what you get within the script: processing data in RAM is much more efficient than disk I/O.

No guarantees this works, but it's just things rearranged a bit and tightened up to remove superfluous code -- and maybe even work:
[code=php]
<html>
<head>
<title>Registration Form</title>
<style>
body{background-color: #ffffe6; width:610px;}
h1 {color: #29a3a3;}
.inputbox {padding: 7px; border: #F0F0F0 2px solid; border-radius: 4px;}
.btn {padding: 10px;background-color: #29a3a3; border: solid thin #000000; color: #FFF; font-weight: bolder; cursor: pointer;}
</style>
</head>
<body>
<?php
// Sanitization and Validation coding will go here

// Initialize and set variables
$studentname = " ";
$studentnumber = " ";
$courses = " ";
$datafile = "coursesfinal.txt";
$in = fopen ('course.txt', 'r') or die ("courses.txt cannot be opened for reading.");
?>
<h1>Course Registration</h1>
<form method="post" action="index.php">
<fieldset><legend><strong>Student Information</strong></legend>
<dl>
<dt>Student Name:</dt>
<dd><input class="inputbox" name="studentname" type="text" id="studentname" value="<?php echo $studentname;?>" required autofocus placeholder="Please enter your first and last name" tabindex="10" size="50"></dd>
<br>
<br>
<dt>Student Number:</dt>
<dd><input class="inputbox" name="studentnumber" type="text" id="studentnumber" value="<?php echo $studentnumber;?>" required placeholder="Please enter using the following format: PX-03-046" tabindex="20" size="50"></dd>
</dl>
<br>
</fieldset>
<br>
<fieldset><legend><strong>Course Selection</strong></legend>
<br>
Select a Course:<select name="courses" tabindex="30">n";
<option value="-1" >Available Courses...</option>
<?php
while(($field = fgetcsv($in, null, ':')) != false) {
if (count($row) > 1) {
echo "
<option value="$field[1]">$field[0] $field[1]</option>";
}
}
?>
</select>
<br>
<br>
<br>
<br>
<br>
<br>
</fieldset>
<div>
<p>
<input name="reset" type="reset" tabindex="40" value="Clear Form" class="btn">
<input name="submit" type="submit" tabindex="50" value="Submit Form" class="btn">
</p>
</div>
</form>
</body>
</html>
[/code]
[/QUOTE]


Hi NogDog,

I changed this 'course.txt', to 'courses.txt', and I see in your coding where the courses should list but no data displays. I see you moved the PHP out of the <head> area - I wasn't sure where it was supposed to be placed.

Thank you for your help - I'm off to bed as my eyes are burning from crying over this. Is that worse than crying over spilled milk? This piece is the tip of the iceberg for this assignment and I have tomorrow off work and Saturday and Sunday to get it done. Hopefully I don't dream about code like I did last night, and I have a good sleep and can look at it in the morning with fresh eyes.
Copy linkTweet thisAlerts:
@NogDogMar 10.2016 — Actually tested it this time, made a few tweaks, and seems to "work". I used this as the courses.txt file:
<i>
</i>Animation Film Design:AFD-250:6
Digital Sculpture:DS-410:4
History of Animation:HA-240:6
Visual Effects:VE-298:4

The revised PHP form file:
[code=php]
<html>
<head>
<title>Registration Form</title>
<style>
body{background-color: #ffffe6; width:610px;}
h1 {color: #29a3a3;}
.inputbox {padding: 7px; border: #F0F0F0 2px solid; border-radius: 4px;}
.btn {padding: 10px;background-color: #29a3a3; border: solid thin #000000; color: #FFF; font-weight: bolder; cursor: pointer;}
</style>
</head>
<body>
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Sanitization and Validation coding will go here

// Initialize and set variables
$studentname = " ";
$studentnumber = " ";
$courses = " ";
$in = fopen ('courses.txt', 'r') or die ("courses.txt cannot be opened for reading.");
?>
<h1>Course Registration</h1>
<form method="post" action="index.php">
<fieldset><legend><strong>Student Information</strong></legend>
<dl>
<dt>Student Name:</dt>
<dd><input class="inputbox" name="studentname" type="text" id="studentname" value="<?php echo $studentname;?>" required autofocus placeholder="Please enter your first and last name" tabindex="10" size="50"></dd>
<br>
<br>
<dt>Student Number:</dt>
<dd><input class="inputbox" name="studentnumber" type="text" id="studentnumber" value="<?php echo $studentnumber;?>" required placeholder="Please enter using the following format: PX-03-046" tabindex="20" size="50"></dd>
</dl>
<br>
</fieldset>
<br>
<fieldset><legend><strong>Course Selection</strong></legend>
<br>
Select a Course:<select name="courses" tabindex="30">n";
<option value="-1" >Available Courses...</option>
<?php
while(($fields = fgetcsv($in, null, ':')) != false) {
if (count($fields) > 1) {
echo "
<option value="$fields[1]">$fields[0] $fields[1]</option>";
}
}
?>
</select>
<br>
<br>
<br>
<br>
<br>
<br>
</fieldset>
<div>
<p>
<input name="reset" type="reset" tabindex="40" value="Clear Form" class="btn">
<input name="submit" type="submit" tabindex="50" value="Submit Form" class="btn">
</p>
</div>
</form>
</body>
</html>
[/code]
Copy linkTweet thisAlerts:
@BlondieCauthorMar 10.2016 — You are great! I Googled the ini_set code to see what it does and from what I read I'm wondering why this hasn't come up in my course material. I see the $datafile = "coursesfinal.txt" is gone which makes sense as per what you explained in your #32 post. And following that the $in = fopen line of code handles the .txt file with the four options. I see that "explode" doesn't need to necessarily be utilized to achieve the desired results. I learn more in the forum than from my course. And it works beautifully - thank you. This is my 7th of 8 courses and I'm struggling with this one more than with the JavaScript. I don't find the learning structure of this one conducive to how I learn. It doesn't build on the previous week demonstrating how everything works together but I'm still hanging on by a thread to learn and understand and complete it successfully for my certificate I've been working on since 2013.
Copy linkTweet thisAlerts:
@NogDogMar 10.2016 — The beauty of PHP is that it has all sorts of built-in functions that can provide many ways to accomplish the same goals. That's also a bit of its ugliness: there's almost always more than one way to do anything, and not necessarily one "correct" or "best" way, so the way I might prefer to do something may be at odds with what someone else would (just as legitimately) do.

A general goal to strive for is simplicity and compartmentalization -- which if/when you get into object-oriented PHP will become especially important (in particular the compartmentalization aspect).

For now, try to keep related tasks together, and try to avoid writing essentially the same code multiple times (a.k.a. "Keep it DRY"): that's where user-defined functions and various looping structures can help a lot.

PS: Those ini_set() and error_reporting() lines are there to make debugging a bit simpler, by showing any warnings or errors right in the browser. In a "real" production environment, I'd turn off the "display_errors" setting (setting it to 0 or FALSE), so as not to potentially spew info on the screen that you would not want a malicious user to see. ?
×

Success!

Help @BlondieC spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...