Solved

PHP mySQL drop down box

Posted on 2011-03-08
17
570 Views
Last Modified: 2013-12-13
Hi Experts,

What im after is help with a php mysql drop down box, ive looked about and non seem to meet my needs, what im after is...

a drop down list of all fields within a table for example companies

then from this list when one is selected and submit is pressed it directs the user to the relevent webpage for that company.

Basiclly... i need a drop down menu which takes the user to their desired webpage based on the drop down selection.

i know how to do the form just not the php part.

Many thanks

James
0
Comment
Question by:NeoAshura
  • 7
  • 6
  • 3
  • +1
17 Comments
 
LVL 13

Assisted Solution

by:darren-w-
darren-w- earned 100 total points
Comment Utility
0
 
LVL 13

Expert Comment

by:darren-w-
Comment Utility
after setting up the select list you will need to configure a redirect to the url of the respective page,  this should take the option value that should be the url,

here is an example using jquery:

http://stackoverflow.com/questions/580281/redirect-automatically-when-selecting-an-item-from-a-select-drop-down-list
0
 
LVL 27

Assisted Solution

by:yodercm
yodercm earned 100 total points
Comment Utility
What you need to do is ...
1.  Retrieve the company names from your database table with a MySQL SELECT statement.
2.  Create the dropdown list with all the company names.
3.  In the action statement for the form, put a php script name (say for example, process.php).
4.  In the action script (example, process.php), retrieve the selected company name from the $_POST array.
5.  Redirect to the appropriate website for the company selected.

In the form, you will need
<form method=post action='process.php'>
and a loop to populate the dropdown values from the retrieved names.  The dropdown input must be named (example, name=companyname), and then in the action script, you will retrieve the company name as
$companyselected = $_POST["companyname"];



0
 
LVL 6

Author Comment

by:NeoAshura
Comment Utility
Thanks all I will look at these at work tomorrow, in repsonce to yodercm could you give an example of how to dowhat your surgested?  Thank you
0
 
LVL 20

Accepted Solution

by:
Mark Brady earned 300 total points
Comment Utility
I would not even use a form. You cause the users to make an extra movement when they could navigate to their page just by selecting their value from dropdown list. The best and fastest way (in my opinion) and very clean is to do the following. Create a php page and combine it with HTML as like this;
I am assuming for this example that you have a table called "companies" and inside the table you have two fields (at least) called "title" and "URL". Obviously you can change this code around to suit your situation. The best thing is, you can copy and paste the code below and as long as you change the mysql call to suit your table it will run properly, AND it is only one script/web page.

<!-- copy from the line below -->
<?php // company.php  - call this whatever you like
include("connection_script.php"); // or put you mysql connection code here

$company_select = "<select name="company" id="company" onchange="navigate(this.value)">";
// the above dropdown list will automatically navigate to the right page upon user selection. Fast and easy.

$sql = "SELECT title,URL FROM `companies` ORDER BY title ASC";
$result = mysql_query($sql)or die(mysql_error());
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$company_title = "{$row['title']}";
$company_URL= "{$row['URL']}";
$company_select .= "<option value='$company_URL'>$company_title</option>";
}
$company_select .= "</select>";

// that's the php part finished. Of course you will probably have much more php code than this. This is //just a small example to show you how it go to the persons page when it is changed.
?>
<html>
<head><title>Test Page</title>
<script language="javascript">
function nav(location)
{
window.location = location;
}
</script>
</head>
<body>
Please select your company <?php echo $company_select; ?>
</body>
</html>
<!-- Copy to the line above -->

That's it! Pretty simple - all in one page and all they do is select their company name from the select box and they are taken straight to their page. Hope this helps you. I haven't tested the code above - just off the top of my head but it should work.
0
 
LVL 6

Author Comment

by:NeoAshura
Comment Utility
thank you for your code there looks very help and could help..

However i get an error on line 5 unexpected T_string.. cant see any problems with it tho.. line 5 is,...

$company_select="<select name="company" id="company" onchange="navigate(this.value)">";

0
 
LVL 20

Expert Comment

by:Mark Brady
Comment Utility
Ahhh yep sorry, the problem is the quote marks, I forgot to escape them. The inner quotes should be single quotes or you can escape the double quotes like this.

$company_select = "<select name=\"company\" id=\"company\" onchange=\"navigate(this.value)\">";

to use single quotes:

$company_select = "<select name='company' id='company' onchange='navigate(this.value)'>";

So only double quotes at the start and finish. Sorry about that like I said it was off the top of my head.
It will work now
0
 
LVL 6

Author Comment

by:NeoAshura
Comment Utility
no worries buddy cheers, i did try the slashes and the single quotes i must of forget to save and upload..

Well it works but when i choose Tesco... it should go to  www.google.com as a test when selected?

im guessing thats how its ment to work is whens it selected go to the URL in the database?

doesnt seem to work do i need a submit button or something?
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 20

Expert Comment

by:Mark Brady
Comment Utility
No, as soon as something is selected from the list, it should perform the javascript function immediately and that function navigates to the URL that you have in the database. Tell me how your table is setup and give me some examples of what is in your table and I will get it working for you
0
 
LVL 20

Expert Comment

by:Mark Brady
Comment Utility
Yes I found the problem. Once again a typo on my part sorry. I put the wrong javascript function name into the selectbox. It should read

$company_select = "<select name='company' id='company' onchange='nav(this.value)'>";

instead of this:

$company_select = "<select name='company' id='company' onchange='navigate(this.value)'>";

The code was trying to find a function called "navigate() instead of nav()

Change that line and try again. One more thing, if these are going to be external links, then make sure that in your "companies" table has the full URL in there so google would be

http://www.google.com

NOT

www.google.com

that will make sure you get directed to the pages properly
0
 
LVL 6

Author Comment

by:NeoAshura
Comment Utility
ok, what i have in my table for example is as follows.

title      URL
Asda      www.yahoo.com
tesco      www.google.com

Urls are for testing purposes, i think these urls would be for example asda.php

when it was finished.
0
 
LVL 6

Author Comment

by:NeoAshura
Comment Utility
only problem is when more companies need to be added i would need to create more pages of php wouldnt i?

is there anyway to make this so you can POST the company selected to the next page as a variable and then do a select statement on the next page to retrieve data for that company?

e.g Address etc?
0
 
LVL 6

Author Comment

by:NeoAshura
Comment Utility
problem solved, i used the following....

many thanks to all experts involved.
<?php
error_reporting(E_ALL);
include 'myphp.php';
?>
<select id="ddlCompanies">
<?php
$sql = "SELECT title FROM companies ORDER BY title";
$rs = mysql_query($sql);
echo $sql;
while($row = mysql_fetch_array($rs)) {
   echo ("<option>" . $row['title'] . "</option>");
}
?>
</select>
<br />
<input type="button" onclick="var val = document.getElementById('ddlCompanies').options[document.getElementById('ddlCompanies').selectedIndex].value; var url = 'companyInfo.php?val=';url+=val;window.location=url;" value="Submit..." />

/// then////

<?php 
error_reporting(E_ALL);
include 'myphp.php';
$val = $_GET['val'];
$sql = "SELECT * FROM companies WHERE title = '" . $val . "'";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs))
{
   echo('Title: ' . $row['title']);
   echo('URL: ' . $row['URL']);
}
   ?>

Open in new window

0
 
LVL 6

Author Closing Comment

by:NeoAshura
Comment Utility
most points awrded to elvin66 for best attempt which helped me reach my answer.
0
 
LVL 20

Expert Comment

by:Mark Brady
Comment Utility
When adding more companies all you need is a php script to add the new company info into the database. Then next time you load the page with the <select> dropdown box you will see that new company. Here's what you need to do to add new companies. you will need to go to each page you want to add and copy the entire URL so you can paste it into the window to add it. Try this:

<?php // add-company.php
include("constants.php"); // remember the constants.php file for connection to mysql

if($_POST['newCompany'] != ""){
// a new company has been added so lets add it to the database.
// first we get the details
$new_company = $_POST['newCompany'];
$new_URL = $_POST['newURL'];
mysql_query("INSERT INTO companies (title,URL) VALUES ('$new_company','$new_URL')or die(mysql_error());
}
// that's the end of the php part. Now for the form.
?>
<html><head><title>New Company Add form</title></head>
<body>
<center>
<h2>Add New Company</h2>
<form action="add-company.php" method="POST">
<table cellpadding=3 cellspacing=0 border=0 style="font:12pt arial">
<th>Company Title</th><th>Full URL</th><th>Action</th></tr>
<tr><td><input type="text" name="newCompany" class="input" /></td>
<td><input type="text" name="newURL" class="input" /></td>
<td><input type="submit" value="Add" /></td></tr></table></form>

</center>
</body>
</html>


ok save the above code as "add-company.php" and put it somewhere but make sure it is in the same folder as the "constants.php" file. Load the page and add a new company and press "Add". Be sure to copy the whole URL not just the www part (http://www.yourwebsite.com). Keep adding companies until you have finished then go back to the page you have the selectbox on and refresh it. you will see those new companies listed in there.

0
 
LVL 20

Expert Comment

by:Mark Brady
Comment Utility
Wow that's a totally different thing altogether from all the code I gave you. how is that redirecting you to the pages? In any case, forget everything I posted, you've gone a different way - wish I had known now i wouldn't have spent the last hour typing up a bunch of code lol. Good luck
0
 
LVL 13

Expert Comment

by:darren-w-
Comment Utility
Hi,

Only thing I did not notice is that there is no backward compatibility, ie if the user is using a screen reader or has JavaScript disabled, in this case none of the  solutions will work as they depend on this, here is the code which handles this:

<?php
//check if posted to self, ie javascript disabled

if (isset($_POST['goto'])) {
    header('Location: ' . $_POST['goto']);
}
//do the drop down
//get data, create associated array for simplicity/testing
$urlList = array("http://www.google.co.uk" => "Google", "http://www.yahoo.co.uk" => "Yahoo", "http://www.msn.co.uk" => "MSN");
//build option list
$ol = null;
$ol.="<select name='goto'>";
foreach ($urlList as $key => $value) {
    $ol.="<option value = '$key'>$value</option>";
}
$ol.="</select>";
?>

<!-- some html -->
<html>
    <head>
        <title>a redirect</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(function(){
                //remove the button as its not needed
                $("input[type='submit']").remove();
                //add js redirect
                $("select[name='goto']").change(function() {
                    window.location = $(this).val();
                });
                
            });
        </script>
    </head>
    <body>
        <form name="redirect" action="<?php echo $_SERVER['PHP_SELF']; ?>" method ="post">
            <?php echo $ol; ?>
            <input type="submit" value="Go" />
        </form>

    </body>
</html>

Open in new window

0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now