use mysql data and put into a drop down - php

i have be been trying to put a count query into a drop down as i am creating a rating type system and based on the number of rows in a database i want to return a scale for example 1-5
<?php
// Ruth Gammack
session_start();
$page = 'index.php';
mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('group4') or die(mysql_error());
//echo "Done";
require_once "./includes/choices.inc.php";
if(isset($_GET["action"])){
switch($_GET["action"]) {
case "add":
addmodule();
break;
case "remove":
removemodule();
break;
case "empty":
emptychoice();
break;
}
reviewChoices();
// close database connection
dbClose($conn);
}
function modules(){
$get = mysql_query('SELECT * FROM module');
if (mysql_num_rows($get) == 0){
echo '<p>There are no Modules available at this time please check back later</p>';
}
else {
while ($get_row = mysql_fetch_assoc($get)) {
echo '<p>'.$get_row['moduleID'].'<br />'.$get_row['ModuleName'].'<br />'.$get_row['ModuleDesc'].'<br />'.$get_row['LecturerID'].'</p>';
// printing the list box select command
$query_disp=('SELECT moduleID, COUNT(*) FROM module');
$result_disp = mysql_query($query_disp);
echo "<select name=”selRating”>";
while($row = mysql_fetch_array($result_disp))
{
echo "<option value='" . $row['moduleID'] . "'>" . $row['moduleID'] . "</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
}
}
}
?>
i have tried many different ways but I have run out of ideas.

Maybe something like this (not tested)?
$query_disp=('SELECT moduleID, ModuleName, ModuleDesc, LecturerID, COUNT(*) AS cnt FROM module GROUP BY moduleID');
$select = "<select name=”selRating”>";
while($row = mysql_fetch_array($query_disp))
{
echo '<p>'.$get_row['moduleID'].'<br />'.$get_row['ModuleName'].'<br />'.$get_row['ModuleDesc'].'<br />'.$get_row['LecturerID'].'</p>';
$select += "<option value='" . $row['moduleID'] . "'>" . $row['ModuleName'] . " " . $row['cnt'] . "</option>";
}
$select += '</select>';
echo $select;

Related

Sorting with MySQL and PHP

So right now I have my MySql database on phpmyadmin connected to my PHP script. It lists 50 different NFL players and their stats from last year. I would like to be able to list a dropdown box to where I can sort the players by any of the categories (i.e. Receptions, Rec Yds, TDs, etc.) but am not sure how I would do this..?? I have a switch statement in there but it doesn't seem to be doing anything right now.
<!DOCTYPE html>
<html>
<!-- Seth Rataiczak -->
<head>
<title>PHP Project</title>
<style>
table,th,td {
border:1px solid navy;
}
body {
background-color:peachpuff;
}
</style>
</head>
<body>
<?php
// database connection
$db_hostname='localhost';
$db_username='root';
$db_password='';
$db_database='Project';
$connection = new mysqli( $db_hostname,
$db_username,
$db_password,
$db_database);
//MySQL Select Statement
$sort = "";
if(isset($_GET['sort'])) {
switch ($_GET['sort'] ) {
case 0:
$sort = ' ORDER BY Team DESC';
break;
case 1:
$sort = ' ORDER BY Pos DESC';
break;
case 2:
$sort = ' ORDER BY Rec DESC';
break;
case 3:
$sort = ' ORDER BY Yds DESC';
break;
case 4:
$sort = ' ORDER BY Avg DESC';
break;
case 5:
$sort = ' ORDER BY Yds/G DESC';
break;
case 6:
$sort = ' ORDER BY TD DESC';
break;
}
}
$sql = "SELECT * FROM NFL_2014_Receiving WHERE Field=1" . $sort;
$result = $connection->query($sql);
if (!$result) die ($connection->error);
$n = $result->num_rows;
$nfl = array();
// echos the table headers
echo "<table>
<tr><th>ID</th><th>Player</th><th>Team</th>
<th>Position</th><th>Receptions</th>
<th>Receiving Yards</th><th>Avg Yds/Catch</th>
<th>Avg Yds/Game</th><th>Touchdowns</th></tr>";
// echos the table data
while ($row = $result->fetch_array(MYSQLI_ASSOC)){
$nfl[$row['iD']] = $row['Player'];
if(!isset($_POST['hide']) || $_POST['hide'] != $row['iD']){
echo "<tr><td width=20>" . $row['iD'] . "</td><td width=150>" . $row['Player'] . "</td><td width=40>" .
$row['Team'] . "</td><td width=30>" . $row['Pos'] . "</td><td width=30>" .
$row['Rec'] . "</td><td width=40>" . $row['Yds'] . "</td><td width=30>" .
$row['Avg'] . "</td><td width=40>" . $row['Yds/G'] . "</td><td width=20>" .
$row['TD'] . "</td></tr>";
}
}
echo "</table><br>";
//dropdown box
echo "<form method='post' action='index.php'><select name='hide'>";
foreach($nfl as $key=>$value){
echo "<option value='".$key."'>".$value."</option>";
}
// submit button
echo "<input type='submit' value='Submit'>";
echo "</select></form>";
?>
</body>
</html>
You are setting a POST method action and you are searching GET for value.
To be clear:
You can change your form method to get <form method='get' action='index.php'> or change your php value $_GET['sort'] to $_POST['sort']
I m quite sure this is your problem but you can echo your $sql variable to see what your query does ;)
the input submit is inside of select tag. must be after select, not inside.
the method of form must be equal to the parameter received, in this case must be GET.
the name of the select must be 'sort' instead of 'hide'

value of dropdown list from mysql

I'm trying to compose an estimate formula, and I stucked with value of dropdown list populated by MySQL.
The idea of this formula is when a user select a service from dropdown list and put the quantity in textfield the program will compute the price for the service.
The value of the prize is selected from MySQL table.
$query="SELECT $con_tent FROM services WHERE $id;
$con_tent= 'price'. '*'. $qunatity
But I don't know how to get the value from dropdwon list.
Probably with Ajax but still don't know how.
I solved this by modyfing code from http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html
<?php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_user, $db_password);
mysql_select_db($db_database) or die("unable to select database:" . mysql_error());
echo "<form action=licz.php method='post'>";
echo " <label for=\"select\"><select name=\"\" value=\"Select\" size=\"1\">";
$query = "SELECT * FROM uslugi ORDER BY id ASC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
global $ff;
$ajdi = $row['id'];
$nazwa = $row['nazwa'];
$options.= "<option value=\"$ajdi\" name=\"oko\">" . $nazwa . $ajdi;
}
echo "<option>";
echo $options;
echo "</option></select>";
echo " <input type=\"submit\" name=\"Submit\" value=\"Submit\">";
echo "</form>";
function wybor() {
global $id;
global $con_tent;
$var = 'price' . '*';
$quantity = 3;
//quantity will by from textfield but now it constant
$id_value = 1;
// here i need to make it dynamic
$id = "id={$id_value}";
$con_tent = $var . $quantity;
}
echo wybor();
$query = "SELECT $con_tent FROM services WHERE $id";
//query
if (!$query) Die("Unable to query: " . mysql_error());
$result = mysql_query($query);
if (!$result) Die("Unable to query: " . mysql_error());
$rows = mysql_num_rows($result);
for ($a = 0; $a < $rows; ++$a) {
$row = mysql_fetch_row($result);
echo $row[0] . " ";
echo $row[1] . " ";
echo $row[2] . " ";
echo $row[3] . "$br";
}
?>
You should apply ajax call to get value for database when there is a change in select box through calling a function on onchange event of javascript.
Read More for jquery AJAX
http://www.sitepoint.com/ajax-jquery/
http://www.tutorialspoint.com/jquery/jquery-ajax.htm

Find previously selected option in while loop

I'm trying to get a drop down menu to keep its selected value when the user hits submit, but it fails due to errors on the form.
I have a while loop returning values from a database to build the options for the drop down, but how do I echo "selected" on the right option?
I have tried if($district == $row["name"]) { echo "selected";} as you see below, but it doesn't work.
<?php
$result = mysql_query("SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = 6 GROUP BY dist.id ORDER BY dist.id ASC", $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo '<option value="{$row["name"]}"'; if($district == $row["name"]) { echo "selected";} ; echo '>' . $row["name"] . "</option>";
}
?>
Sorry for the delay. None of the suggested answers worked for me. Any other ideas?
Can you try this,
<?php
$result = mysql_query("SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = 6 GROUP BY dist.id ORDER BY dist.id ASC", $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
$district = $_REQUEST['name']; // You need pass the value you have been submitted
while ($row = mysql_fetch_array($result)) {
$selected ="";
if(trim($district) == trim($row["name"])) { $selected = "selected";}
echo '<option value="{$row["name"]}" '.$selected.' >' . $row["name"] . "</option>";
}
?>
Try this..
if($district == $row["name"])
{
echo "<option value='$district' selected>$district</option>";
}
I just found the answer. This is what I did:
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row["name"] . '"';
if($row["name"] == $district) { echo 'selected';} ;
echo '>' . $row["name"] . '</option>';
}
It seems to have been this line
echo '<option value="{$row["name"]}"';
that was causing the problem.

Updating to MySQLi and having some trouble

So I've spent a bit of time looking at MySQLi and I'm having trouble updating a script with the new functions. This script is used for a dynamic dropdown form, using data sent to it using JS. You can find a live version of the script here to check out what I'm takling about. I've looked up and down my code and have compared it to other MySQLi examples and I'm just not sure where I'm going wrong.
Now, the first dropdown doesn't even initiate a query, all the PHP does is return predefined results as it's just simpler for the first option. What's weird, to me, is that even the first drop down is now not working when it does not rely at all on the MySQLi connection. It all worked before updating, just for reference.
Here's my script:
$db = new mysqli($dbHost, $dbUser, $dbPass, $dbDatabase);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
//prevents injections
//any order
isset($_GET['type'])?$type = urldecode($_GET['type']):"";
isset($_GET['source'])?$source = $db->real_escape_string(urldecode($_GET['source'])):"";
isset($_GET['range'])?$power = $db->real_escape_string(urldecode($_GET['range'])):"";
isset($_GET['setpoint'])?$setpoint = $db->real_escape_string(urldecode($_GET['setpoint'])):"";
//forms the query depending on what data is recieved through GET
//first option on the bottom; last option on the top to avoid conflicts
if (isset($_GET['setpoint'])) {
$query = "SELECT DISTINCT stp FROM meters WHERE sio='$range' AND pso='$power' AND stp='$setpoint' ORDER BY model";
} elseif (isset($_GET['power'])) {
$query = "SELECT DISTINCT stp FROM meters WHERE sio='$range' AND pso='$power' ORDER BY model";
} elseif (isset($_GET['range'])) {
$query = "SELECT DISTINCT pso FROM meters WHERE sio='$range' ORDER BY model";
} elseif (isset($_GET['source'])) {
$query = "SELECT DISTINCT sir FROM meters WHERE sio LIKE '%$source%' ORDER BY sir";
}
//creates a result array from query results
isset($query)?$result = $db->query($query):"";
//outputs dropdown options dependent on what GET variables are set
//first option on the bottom; last option on the top to avoid conflicts
if (isset($_GET['setpoint'])) {
while ($row = $result->fetch_assoc()) {
echo "<option value='" . $row['stp'] . "'>" . $row['stp'] . "</option>";
$result->free();
}
} elseif (isset($_GET['power'])) {
echo "<option>Please Choose Setpoint Options</option>";
while ($row = $result->fetch_assoc()) {
$row{'stp'} = ucfirst($row{'stp'}); //capitalizes the first letter; necessary?
echo "<option value='" . $row['stp'] . "'>" . $row['stp'] . "</option>";
$result->free();
}
} elseif (isset($_GET['source'])) {
echo "<option>Please Choose Input Range</option>";
while ($row = $result->fetch_assoc()) {
echo "<option value='" . $row['sir'] . "'>" . $row['sir'] . "</option>";
$result->free();
}
} elseif (isset($_GET['type']) && $_GET['type'] == "Digital") {
echo "<option>Please Choose Input Source</option>";
echo "<option value='RS232C'>RS232C</option><option value='RS422'>RS422</option><option value='RS485'>RS485</option><option value='current loop'>current loop</option>";
$result->free();
} elseif (isset($_GET['type']) && $_GET['type'] == "Analog") {
echo "<option>Please Choose Input Source</option>";
echo "<option value='DC current'>DC Current</option><option value='DC voltage'>DC Voltage</option><option value='AC current'>AC Current</option><option value='AC voltage'>AC Voltage</option><option value='process'>Process</option><option value='thermocouple'>Thermocouple</option><option value='RDT'>rdt</option>";
$result->free();
}
edit: This is my old code using the deprecated method.
$con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL Server. Error: " . mysql_error());
mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error());
//prevents injections
//any order
isset($_GET['type'])?$type = urldecode($_GET['type']):"";
//$type = mysql_real_escape_string(urldecode($_GET['type']));
isset($_GET['source'])?$source = mysql_real_escape_string(urldecode($_GET['source'])):"";
isset($_GET['range'])?$power = mysql_real_escape_string(urldecode($_GET['range'])):"";
isset($_GET['setpoint'])?$setpoint = mysql_real_escape_string(urldecode($_GET['setpoint'])):"";
//forms the query depending on what data is recieved through GET
//first option on the bottom; last option on the top to avoid conflicts
if (isset($_GET['setpoint'])) {
$query = "SELECT DISTINCT stp FROM meters WHERE sio='$range' AND pso='$power' AND stp='$setpoint' ORDER BY model";
} elseif (isset($_GET['power'])) {
$query = "SELECT DISTINCT stp FROM meters WHERE sio='$range' AND pso='$power' ORDER BY model";
} elseif (isset($_GET['range'])) {
$query = "SELECT DISTINCT pso FROM meters WHERE sio='$range' ORDER BY model";
} elseif (isset($_GET['source'])) {
$query = "SELECT DISTINCT sir FROM meters WHERE sio LIKE '%$source%' ORDER BY sir";
}
//creates a result array from query results
isset($query)?$result = mysql_query($query):"";
//outputs dropdown options dependent on what GET variables are set
//first option on the bottom; last option on the top to avoid conflicts
if (isset($_GET['setpoint'])) {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'stp'} . "'>" . $row{'stp'} . "</option>";
}
} elseif (isset($_GET['power'])) {
echo "<option>Please Choose Setpoint Options</option>";
while ($row = mysql_fetch_array($result)) {
$row{'stp'} = ucfirst($row{'stp'}); //capitalizes the first letter; necessary?
echo "<option value='" . $row{'stp'} . "'>" . $row{'stp'} . "</option>";
}
} elseif (isset($_GET['source'])) {
echo "<option>Please Choose Input Range</option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'sir'} . "'>" . $row{'sir'} . "</option>";
}
} elseif (isset($_GET['type']) && $_GET['type'] == "Digital") {
echo "<option>Please Choose Input Source</option>";
echo "<option value='RS232C'>RS232C</option><option value='RS422'>RS422</option><option value='RS485'>RS485</option><option value='current loop'>current loop</option>";
} elseif (isset($_GET['type']) && $_GET['type'] == "Analog") {
echo "<option>Please Choose Input Source</option>";
echo "<option value='DC current'>DC Current</option><option value='DC voltage'>DC Voltage</option><option value='AC current'>AC Current</option><option value='AC voltage'>AC Voltage</option><option value='process'>Process</option><option value='thermocouple'>Thermocouple</option><option value='RDT'>rdt</option>";
}
You are freeing your $result inside the while loop. This will cause the loop to fail on the second iteration.
Since you are freeing the result in all of the ifs, why don't you just do it once at the end?
...
} elseif (isset($_GET['type']) && $_GET['type'] == "Analog") {
echo "<option>Please Choose Input Source</option>";
echo "<option value='DC current'>DC Current</option><option value='DC voltage'>DC Voltage</option><option value='AC current'>AC Current</option><option value='AC voltage'>AC Voltage</option><option value='process'>Process</option><option value='thermocouple'>Thermocouple</option><option value='RDT'>rdt</option>";
}
$result->free();
However this doesn't explain why analog and digital won't work still..

populate drop down list from mysql database and don't repeat values

I am populating a drop down menu from mysql database. It works well, But I want it not to repeat values. (i.e if some value is N times in database it comes only once in the drop down list)
Here is my code:
<?php
mysql_connect('host', 'user', 'pass');
mysql_select_db ("database");
$sql = "SELECT year FROM data";
$result = mysql_query($sql);
echo "<select name='year'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['year'] . "'>" . $row['year'] . "</option>";
}
echo "</select>";
?>
Use DISTINCT in your query.
"SELECT DISTINCT year FROM data";
just change Your query. is better
$sql = "SELECT distinct year FROM data";
Another technique:
select year from table group by year
in PHP side you have to do this
$all_data = array();
echo "<select name='year'>";
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
array_push($all_data,$row["column"]);
}
$all_data = array_unique($all_data);
foreach($all_data as $columns => $values){
print("<option value='$value'>$value</option>");
}
echo "</select>";
Here is a simple trick. Take a boolean array. Which value has not come in list print it in list and which value has come in list already once, set it as true through indexing the boolean array.
Set a condition, if boolean_array[ value ] is not true, then show value in list. Otherwise, don't.
mysql_connect('host', 'user', 'pass');
mysql_select_db ("database");
$sql = "SELECT year FROM data";
$result = mysql_query($sql);
echo "<select name='year'>";
while ($row = mysql_fetch_array($result)) {
if($bul[$row['year']] != true){
echo "<option value='" . $row['year'] . "'>" . $row['year'] . " </option>";
$bul[$row['year']] = true;
}
}
echo "</select>";
?>

Categories