Create dynamic select list from mysql table

Displaying a select box is really simple, straight forward. But sometimes we may need to show dynamic select boxes using the mysql table row data. Now most of the websites uses a content management system and contents are being updated from the administration modules.



Lets consider the case of a online book shop. You may have seen the filtering options in book listing pages. We can create a simple filter using the below code

<select name="books">
 <option value="25">Best Sellers</option>
 <option value="26">New Books</option>
 <option value="27">Popular Books</option>
</select>



This is a static select box. We cannot add a new option without altering the html code. So we can make this a dynamic select box.


Step 1:

Create a mysql table named "books_filter"
CREATE TABLE `books_filter` (
 `id` INT(11) NOT NULL AUTO_INCREMENT,
 `filter_name` VARCHAR(50) NULL DEFAULT NULL,
 PRIMARY KEY (`id`)
)
ENGINE=InnoDB;


Step 2:
Add the values to books_filter tables using INSERT query.
INSERT INTO `books_filter` (`filter_name`) VALUES ('Best Sellers');
INSERT INTO `books_filter` (`filter_name`) VALUES ('Educational');

Step 3:
Connect to database and fetch the rows from table

<?php
//connecting to mysql
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

//choosing a database
mysql_select_db('database_name', $link);

//fetching values from table
$fetchQuery = "SELECT id, filter_name  FROM books_filter";
$fetchResult = mysql_query($fetchQuery) or die(mysql_error());
?>





0 comments:

Post a Comment