PHP Drop Down Menus - php

I wonder whether someone may be able to help.
I posted a similar message to this little three days ago, but I think that my explanation of the problem wasn't particualrly good so I thought I'd start afresh. I will say that I am new to programming in PHP so please bear with me.
I have three mySQL tables, 'userdetails', 'detectors' and 'detectorsearchheads' with the following fields:
userdetails
userid
name
detectors
userid
detectorid
detectordescription
detectorsearchheads
userid
detectorid
detectorsearchheadid
detectorsearchheaddescription
What I would like is to have a drop down menu on my HTML form that through PHP, shows the list of detectors applicable to the user that is logged on. In turn I would then like another drop down menu that again is user specifc, but additionally only shows the detector search heads applicable to the value selected from the first drop down menu.
I appreciate that there may be other ways to do this but I am more comfortable with PHP.
I just wondered whether someone could possibly please show me what I need to do to get this to work. As I said earlier I am fairly new to PHP, so the simpler the better.
Many thanks and regards
Chris
UPDATED CODE
<?php
mysql_connect("hostname", "username", "password") or die("Connection Failed");
mysql_select_db("databasename")or die("Connection Failed");
$query = "SELECT * FROM detectors WHERE `userid` = '1' ORDER BY 'detectorname' ASC";
$result = mysql_query($query);
?>
<select name="detectorname">
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['detectorname'];?>"> <?php echo $line['detectorname'];?> </option>
<?php
}
?>
</select>

Check this tutorial for example.
Before that you have to generate the html and js code with php. Basicly, get the data from database, and generate needed list. For example:
echo "<li>".$dataFromDatabase."</li>";

You will need CSS/JS to display the Drop Down Menu. With PHP you will prepare the text to be displayed.
After the mysql query, the result should be echoed in appropriate format.
For Eg. if your CSS displays list items(li) as menu, you need to do what 'Waltsu' said.
$result = mysql_query("..."); //your specific query
while ($row = mysql_fetch_assoc($result))
{
echo '<li>'.$row['detectordescription'].'</li>';
//so on
}

Related

Can't print a specific cell from sql query

I'm having trouble with my php code. I have a table in my DB and every entry has a name, type, location etc. The basic idea is that after entering the name from the previous page (that's why there's a POST variable at the start of the code), you get transfered to this page and it prints the corresponding type. The problem is that even though I'm sure the code is correct and I've tried a few different solutions (I've been searching for a while in the forum), I can't print the type variable.
<?php
$k = $_POST['sub1'];
$con = mysqli_connect("localhost","root","","qr code");
$query = mysqli_query($con, "SELECT type FROM array1 WHERE name ='".$k."'");
while($row = mysqli_fetch_assoc($query)) {
echo $row['type']; }
?>
Any ideas? It's probably a very simple solution, but I'm totally stuck now so I'm sorry if it's too basic :P

While loop to display multiple results

So basically, I have an HTML form that asks a user to select an option from a dropdown list. The list is populated with a mysql query, but also includes an additional option labeled as 'All.' If the users selects all I want it my PHP script to run a timecard for so and so and then underneath that do the same thing for the next employee, so on and so forth. So far, it works fine if you select just one person, but if you select all it says there are no results to display :/. Any help is appreciated.
if ($empfullname == 'All') {
$query = "select fullname from ".$db_prefix."info order by fullname asc";
$result = mysql_query($query);
} else {
print timecard_html($empfullname, $local_timestamp_in_week);
}
while ($row=mysql_fetch_array($result)) {
print timecard_html(stripslashes("".$row['empfullname'].""), $local_timestamp_in_week);
}
Also, I know mysql is depreciated, but that is what I know and I am just trying to make it work with this. Thanks.
Now, something looks off in your code. When doing your select statement, you are selecting 'fullname'. But when printing, you are using 'empfullname'. Kindly correct this first.

Use dropdown list selection as mySQL query parameter

I had asked a similar question a few days ago but think I was trying to do to much at one time. I am hoping someone can help get me started on this.
I have two drop down lists, one will be populated with years (2012, 2011 etc) and I have some mySQL databases called "db_2012", "db_2011" etc. In these databases are tables representing months.
I would like the user to select a year and then use that selection to query the correct db and return a list of table names which will be used to populate the second drop down list. Then click a button "See Results" to query the selected table and show the results.
I am putting this on a wordpress website and am using a php template file that I created. This is still new to me and what I have so far doesnt work like I want it too, it is basically setup now that you select a year and select a month (not populated from db) and click a button. It makes the query and my table is displayed, but I need this solution to be more dynamic and work as described above. Thanks for the help.
echo '<form action="" method="post">';
echo'<select name="years" id="years">';
foreach($yearList as $year){
echo'<option value="'.$year.'">'.$year.'</option>';
}
echo'</select><br />';
echo '<select name="monthList" id="months">';
foreach($monthList as $month) {
echo'<option value="'.$month.'">'.$month.'</option>';
}
echo '</select>';
echo '<input type=\'submit\' value=\'See Results\'>';
echo '</form'>
$yearList and $monthList are just pre populated arrays. So now from here I want to click the See Results button and query my sql database using the parameters from the drop down selections.
$database = $_POST['yearList'];
$month = $_POST['monthList'];
$wpdbtest_otherdb = new wpdb('Username', 'Password', $database, 'localhost');
$qStr = "SELECT * FROM $month";
$myResults = $wpdbtest_otherdb->get_results($qStr, OBJECT);
It sounds like you want to send an AJAX call to a separate php page for security and processing, then have the PHP return XML that you parse back into the second selection box via the AJAX callback. It can be a little messy, but it allows you to check for weird form values that users might inject.
Edit: The PHP will receive your AJAX parameters as parts of the $_GET or the $_POST array. From there, you can do your checks and db call (or not), then add header("Content-Type:text/xml"); so the server sends it back with the correct header. After that you'll need to echo the XML-formatted data you want the JavaScript to receive. Just remember not to echo anything other than the XML if the request is supposed to go through.

select from dropdown list containing sql data

Pls help.
I am working on a php project and this requires adding and altering data from the SQL database. There are two tables involved with this: emp which contains employee details and pay containing payroll records for each employee.
I would like to have a dropdown list containing all employee names (empname) from the database. Below the list is a form where the user shall input the payroll details. These details will then be saved into the SQL pay table corresponding to the employee name selected.
I've tried searching over the web but it doesn't seem to similar to my problem. How should I do this? Thanks!
Wihtout knowing any more details about your datbase, table structure and other stuff, this is closes that I could get.
<?php
/* Connect to SQL and retreive data */
$sqlConf = array('u'=>'username','p'=>'password','h'=>'localhost','d'=>'myDatabase');
$sqlCon = mysql_connect($sqlConf['h'], $sqlConf['u'], $sqlConf['p']);
if ($sqlCon) {
$emp = array();
mysql_select_db($sqlConf['d'], $con);
$result = mysql_query("SELECT * FROM emp");
while($row = mysql_fetch_array($result)) { $emp[] = $row; }
mysql_close($sqlCon);
}
/* Generate select box contents */
$html = '<select name="emp">';
$html .= '<option>Employee list</option>';
if (!empty($emp)) {
foreach ($emp as $k => $v) {
$html .= '<option value="'.$v['empid'].'">'.$v['empname'].'</option>';
}
}
$html .= '</select>';
/* Output */
echo $html;
?>
Sounds like you need to learn some basic php/SQL. The basic outlines of the problem are:
Query the dropdown list from SQL, and display in an option-select.
When they the form submit, send a corresponding query to update the database.
Is there some particular aspect of this problem that you can't get past?
This can be solved in any number of ways and the overall structure, design and layout of your application would dictate which route to go.
You could have classes that represent your database objects, classes that represent your forms, you could print your forms by mixing php and html like a crazy person and so on and so on.
Then it all depends on if you will be using ajax or not.
So give us a bit more information about how your application is designed and that will probably help.
If you have not started at all I would suggest you to look into some of the many frameworks. Zend Framework or Symphony for example. They have a good way of handling db abstractions and forms creation etc.

PHP Script for Datepicker to select and display database from Mysql

After spending 3 days on internet and struggling with so many different forums , i have found a match and similar case of my problem here.
Friends, I am zero in PHP, but still i have managed to do something to fulfill my requirement.
I am stuck with one thing now..So i need help on....
I am using one html+php form to submit database into mysql.
I created a display of that table through php script on a webpage.
Now i want a datepicker option on that displayed page by which i should able to select the date range and display the data of that date range from my mysql table.
And then take a export of data displayed of selected date range in excel.
This displayed page is login protected, so i want after login the next thing comes in should show a sate selection option which should be fromdate to to date , and then records should displayed from the database and i can take export of those displayed results in excel file.
The code i am using on this page is below which do not have any thing included for excel export and date picker script, I am pasting the code here and request you to please include the required code in it as required.
Thanks In advance
<?php
//database connections
$db_host = 'localhost';
$db_user = '***********';
$db_pwd = '*************';
$database = 'qserves1_uksurvey';
$table = 'forms';
$file = 'export';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$table} ORDER BY date desc");
if (!$result) {
die("Query to show fields from table failed");
}
$num_rows = mysql_num_rows($result);
$fields_num = mysql_num_fields($result);
echo "$num_rows";
echo "<h1></h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
?>
</body></html>
This isn't a "write my code for me, please" site, so you're going to need to be a little more engaging and pro-acive. But we can certainly provide some guidance. Let's see...
Currently you have a page which displays all records from a given table, is that correct? And you need to do two things:
Before displaying any records, have the user select a date range. And keep the date range selection on the page so the user can re-select.
Provide a button which lets the user export the selected records to Excel.
For either of these, you're going to need to add an actual form to the page. Currently there isn't one. For the date picker, I recommend (naturally) using the jQuery UI datepicker. So the form for that would look something like this:
<form method="POST" action="myPHPFile.php">
<input type="text" id="fromDate" name="fromDate" />
<input type="text" id="toDate" name="toDate" />
<input type="submit" name="filterDate" value="Submit" />
</form>
<script>
$(function() {
$("#fromDate").datepicker();
$("#toDate").datepicker();
});
</script>
You may have to wrap the JavaScript in a $(document).ready(){} in order to make it work correctly, you'll want to test that. Anyway, this will give you a form to submit the dates to your script. Wrap the parts of your script which output data in a conditional which determines if the form values are present or not. If they're not, don't fetch any records. If they are, do some basic input checking (make sure the values are valid values, make sure fromDate is before toDate, etc.) and construct your SQL query to filter by date range. (Do take care to avoid SQL injection vulnerabilities here.)
For the Excel output, you may be able to find a ready-made solution for you that just needs a little tinkering. If I were to create one from scratch, I'd probably just output to a .csv file rather than a full Excel file. Most users don't know/care the difference. In that case, you'd just want to either create a second script which is nearly identical to the existing one or add a flag to the existing one which switches between HTML and CSV output, such as via a hidden form field.
For the output of the CSV, first make sure you set your response headers. You'll want to write a header to tell the browser that you're outputting a CSV file rather than text/html, and possibly suggest a file name for the browser to save. Then, the form inputs the SQL query will all be pretty much the same as before. The only difference is in the "HTML" that's being output. Rather than HTML tags, you'd wrap the records in commas, double-quotes (where appropriate), and carriage returns.
There's really nothing special to outputting a "file" vs. "HTML" because the HTTP protocol has no distinction between the two. It's always just text with headers.
Now, I'm sure you have more questions regarding this. And that's fine. In fact, we like to encourage asking (and, of course, answering) questions here. So please feel free to ask for clarification either in comments on this answer (or other answers), or by editing and refining your original question, or by asking an entirely new question if you have a specific topic on which you need help. Ideally, a good question on Stack Overflow consists of sample code which you are trying to write, an explanation of what the code is supposed to be doing, a description of the actual resulting output of the code, and any helpful information relevant to the code. As it stands right now, your question provides code somewhat unrelated to what you're asking, and you're just requesting that we add some features to it outright for you.

Categories