php: populating 3 listboxes

Status
Not open for further replies.

Richlife

New member
Mar 30, 2008
1
0
0
I was converting old asp files to php.
But I'm stuck at this point.
I'm looking for a triple combo listboxes where one has "book" the other "chapter" and the third "verse". The book is populated by a database table. Once book is selected then chapter is populated and then verse.
Any tutorial related to this?
 


This is your first post and you don't even say "please" or "thanks", so.... fuck off.
 
PHP:
<?php
mysql_connect("localhost", "username", "password") or die (mysql_error()); //Connect to database
mysql_select_db("books") or die (mysql_error()); // Select database
?>
<select name="book">
	<option value="0">Select Book...</option>
<?php
$query = mysql_query("SELECT book FROM `table` GROUP BY book"); // Select all books from the database and group by books
while ($r = mysql_fetch_array($query)) { // Loop through the results
	echo "<option value=\"".$r['book']."\">".$r['book']."</select>"; // Display each result in the list box
}
?>
</select>
<select name="chapter">
	<option value="0">Select Chapter...</option>
<?php
if (isset($_POST['book'])) { // Check if we have a book to look for
	$book = preg_replace("/[^0-9A-Za-z\s]/", "", $_POST['book']); // Strip any unwanted characters out
	$query = mysql_query("SELECT chapter FROM `table` GROUP BY chapter WHERE `book` = '".$book."'"); // Select the chapters from the book and group by the chapter
	while ($r = mysql_fetch_array($query)) {
		echo "<option value=\"".$r['chapter']."\">".$r['chapter']."</select>";
	}
}
?>
</select>
<select name="verse">
	<option value="0">Select Verse...</option>
<?php
if (isset($_POST['chapter'])) {
	$chapter = preg_replace("/[^0-9A-Za-z\s]/", "", $_POST['chapter']);
	$query = mysql_query("SELECT chapter FROM `table` GROUP BY chapter WHERE `book` = '".$book."'");
	while ($r = mysql_fetch_array($query)) {
		echo "<option value=\"".$r['verse']."\">".$r['verse']."</select>";
	}
}
?>
</select>

I have not checked this script and it is running under the following assumptions
- The database is structed as individual verses each with a corresponding book and chapter (so that it groups the books and chapters)
- There are no foreign characters in the chapters or verses only A through Z and 0 through 9.
- No javascript involved so they need 3 page refreshes to get a verse, could be page consuming

Also it doesn't check if any verses exist or if somebody tries to screw you over and throw in a weird article is doesn't check if it exists before throwing it into an array which would give a few nasty errors.

But that is a quick and dirty script for you, enjoy :)
 
Status
Not open for further replies.