How to retrieve data from database whenever select in drop down list in php

Hello!

I just started learning PHP and MYSQL a few weeks ago and Im having a little trouble. Im trying to display data from my database when a user selects an option from a drop-down list. I was able to display an error if the user made no selection, then I added more code to query the database and I started receiving errors once I made a selection.

Ive been working on this for a couple of days now and I have ran out of ideas. Any help would be greatly appreciated!

Thank you!

HTML

Option 1: Select a field to display current book inventory OR Option 2: Select an author to display his/her books

PHP

// create global vars $inventory = ""; $author = ""; $query = ""; $error = ""; // Connect to MySQL Server $dbConnection = mysqli_connect[ $dbHost, $dbUser, $dbPassword, $dbName ]; if [ mysqli_connect_errno[] ] {// if the connection in previous statement failed: die[ "Could not connect to the database server: " . mysqli_connect_error[] . " " . mysqli_connect_errno[] . "" ]; //die [] : quit or exit the program completely after displaying the error3 and the actual error } // get values from selection if [$_GET['submitForm']] { $inventory = $_GET['inventory']; $author = $_GET['authorInfo']; $error = validate[$inventory,$author]; } // Build a SELECT query function validate[$inventory,$author] { if [[$inventory == 'select'] && [$author == 'select']] { return "You must select an option!"; } else if [[$inventory != 'select'] && [$author != 'select']] { return "You may only select one option!"; } elseif[$_GET['inventory']== 'all' and $_GET['authorInfo']== 'select']{ $query= "SELECT * FROM books"; //Get all books by selected author } elseif[$_GET['inventory']== 'select' and $_GET['authorInfo']!= 'select']{ $query= "SELECT books.Title, authors.Name FROM books, authors, books_authors WHERE books.ID = books_authors.BID and authors.ID = books_authors.AID and Name = '". $_GET['authorInfo'] . "'"; //Field info for specific author }else{ $query = "SELECT books." . $_GET['inventory'] . " FROM books, authors, books_authors WHERE books.ID = books_authors.BID and authors.ID = books_authors.AID and Name ='" . $_GET['authorInfo'] . "'"; } } // Query the database if [$query != Null] { if [ ![ $result = mysqli_query[$dbConnection, $query] ] ] { print[ "

Could not execute query!

" ]; die[ mysqli_error[] . "" ]; } // end if else { echo "

" . $error . "

"; } } ?> " ]; foreach [ $row as $value ] print[ "" ]; print[ "" ]; } } else { echo "No results returned."; } //Release the returned data to free mysql resources mysqli_free_result[$result]; mysqli_free_result[$inventory]; mysqli_free_result[$author]; //Close the database connection: mysqli_close[ $dbConnection ]; ?> No Query Selected"; } ?> $value

Video liên quan

Chủ Đề