Tutorial to get values from database on selection of dropdown in PHP
PHP Fetch Tutorial
Fetching Data From Database on selection of dropdown value
Step 1:
Get the list of countries from database and populate in drop-down.
[php]
$ctry_qry = mysql_query(“SELECT * FROM countries ORDER BY name;”);?>
//Calling Function
<select name="”ctry”"> <option value="”"">Select Country</option></select>
<select name="”ctry”"><option value="”<?PHP">”><!–?PHP echo $ctry[‘name’]; ?–></option></select>
[/php]
Consider that we choose India from the dropdown list.
Step:2
Add a simple javascript function which will run onchange
[javascript]
function reloaddata(ctryid) {
window.location.href="http://localhost/rotatetheglobe/admin/try.php?ctryid=" + ctryid;
}
[/javascript]
Step:3
Reload the page in JS and pass the currently selected country id
Step:4
Get the country id from query string and fetch the required values from the database
[php]
<?PHP</pre>
<div><code>if</code><code>(isset(</code><code>$_REQUEST</code><code>[</code><code>’ctryid'</code><code>])) {</code></div>
<div><code>$ctryinfo_qry</code> <code>= mysql_query(</code><code>"SELECT * FROM country_info where ctry_root_id=’"</code><code>.</code><code>$_REQUEST</code><code>[‘ctryid</code><code>’]."'</code> <code>ORDER BY ctry_info_id ;");</code></div>
<div><code>?></code></div>
<pre>[/php]
Fetch array is used to fetch the respective row from record set . Using fetch array in while loop is used get a new row of MySQL information until the condition is TRUE.When there are no more rows the function will return FALSE causing the while loop to stop!
[php]
<textarea id="msgpost" name="ctry_about" rows="10" cols="50"> <?php echo $ctry_inf[‘ctry_about’];?></textarea>
<!–?php } ?–>
[/php]
CLICK HERE to view the complete output
Possible Errors to occur:
- JS Error
- Couldn’t get the value from the query string
- Page not found
Must Follow
- Make Sure the querystring variable and the $_REQUEST variable is same
- Make sure your onchange function is same name as that you call in your code.
Must know before reading this article
- PHP Basics
- HTML Basics
- DB Handling
Coming Up:
- How to configure a site to work in your local host when you are running windows
No comments yet.