I am presenting a list of options to the user based on a database query. The results are being fetched correctly however they are currently unordered and I would like to display them in alphabetical order in the option list. I have tried several solutions so far with "ORDER BY" on the query level however with no success. Is there a simple way to achieve this? (The list contains 1000+ results) The code is as follows:
<?php
$user_id = $_SESSION['user_id'];
$sql = "SELECT * FROM add_bulding WHERE description<>''";
$query = $this->db->query($sql);
$building_title = $query->result_array();
?>
<div>
<select>
<option value="">Select Building</option>
<?php foreach ($building_title as $value) { ?>
<option value = "<?php echo $value['id']; ?>">
<?php echo $value['title']; ?>
</option>
<?php
}
?>
</select>
</div>
Try changing your query to:
$sql = "SELECT * FROM add_bulding WHERE description<>'' ORDER BY title DESC";
Sounds like you want a query like:
SELECT id, title FROM add_bulding WHERE description<> ORDER BY title desc
Alternately, you can sort it in php:
<?php
$tmp = array();
foreach ($building_title as $value){
$tmp[$value['id']] = $value['title'];
}
ksort($tmp);
foreach ($tmp as $k => $v) {
print "<option value=\"" + $k + "\">" + $v + "</option>\n";
}
?>
However, in either case, be sure to sanitize your values so you don't end up with XSS problems.
Try this query :
$sql = "SELECT * FROM add_bulding WHERE description<>'' ORDER BY title";
If you want to get title data with alphabetical order then you can write 'ASC' or do not need to write any after ORDER BY title.
But you want to get title data with descending order then you need to write 'DESC' after ORDER BY title
I hope you will get solution.
Related
Not experienced with creating forms in PHP.
I can get my form to produce a dropdown list that has one of my rows listed as an option, but as soon as I try to concatenate 2 rows together (from the same table) for option output...
a) It just doesn't work and I get errors
b) I get the first row as a single option, then my next row as a separate option.
I know there is a simple solution to this, but I am an online student just learning, and I can't seem to find a good example of the code to write it. I'm pretty sure it's an issue of quotes not being placed correctly.
MySQLTable Data:
Table Name: courses
Table Rows: course_id, course_name, max_enrolment
Sample Data: LO-COMP-8001, Intro to HTML, 20
function select_course(){
global $open;
$select = "SELECT * FROM courses";
$result = mysqli_query($open, $select);
return $result;
}
<form action="insert.php" method="post">
<dl>
<dt>Select Course</dt>
<dd><select name="course_id">
<?php // CREATE dropdown menu
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {
foreach ($row as $selection) {
echo "<option value=\"$selection\">$selection</option>";
}}
?>
</select>
</dd>
</dl>
Then there are a few more form fields such as student name and student id afterwards...
Goal Output:
course_id course-name
"LO-COMP-8001 Intro to HTML" ... as a single connected dropdown option and other remaining courses in a dropdown menu
Current Output:
LO-COMP-8001 (as an option)
Intro to HTML (as another option! ... No good)
20 (must be hidden, I need to check if course is full in another function and either allow or deny a student to enrolled etc.)
I have tried:
// output is the one mentioned above..
echo "<option value=\"$selection\">$selection</option>";
// or alternatively...
echo '<option value="'.$row['course_id'].'">'.$row['course_id'].'</option>';
But the second option creates all kinds of weird results.
This is what I am experimenting with right now...
echo '<option value="'.$row['course_id'] $row['course_name']'">'.$row['course_id'] $row['course_name'].'</option>';
But there is a bunch of issues with quotes and square brackets, and I just don't know how to format it correctly for the output.
Any assistance is appreciated.
$row holds the entire row as an associative array therefore no need for the 'foreach' loop.
function select_course(){
global $open;
$select = "SELECT * FROM courses";
$result = mysqli_query($open, $select);
return $result;
}
<form action="insert.php" method="post">
<dl>
<dt>Select Course</dt>
<dd><select name="course_id">
<?php // CREATE dropdown menu
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {?>
<option value="<?php echo $row["course_id"]; ?>"><?php echo $row["course_name"]; ?></option>
<?php }
?>
</select>
</dd>
</dl>
</form>
I was able to come up with another solution as well:
Once the foreach loop was removed, I tried cleaning up the code some... I'm not sure if this is uncommon or 'bad' style, but it does work.
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {
$course_id = $row['course_id'];
$course_name = $row['course_name'];
echo "<option value=\"$course_id\">$course_id $course_name</option>";
Results in: LO-COMP-8001 Intro to HTML as a single option, plus all my other courses in the database.
I have a HTML etc.. tags now what I want to achieve is upon a selection of ie. i want to load the related info from database to in a new tag with as many tags.
I am using PHP to do achieve this now at this point if for example i choose option1 then the query behind it retrieves relevant information and stores it in a array, and if I select option2 exactly the same is done.
The next step I made is to create a loop to display the results from array() but I am struggling to come up with the right solution to echo retrieved data into etc. As its not my strongest side.
Hope you understand what I am trying to achieve the below code will clear thing out.
HTML:
<select id="workshop" name="workshop" onchange="return test();">
<option value="">Please select a Workshop</option>
<option value="Forex">Forex</option>
<option value="BinaryOptions">Binary Options</option>
</select>
PHP:
$form = Array();
if(isset($_POST['workshop'])){
$form['workshop'] = $_POST['workshop'];
$form['forex'] = $_POST['Forex'];
$form['binary'] = $_POST['Binary'];
//Retrieve Binary Workshops
if($form['workshop'] == 'Forex'){
$sql2 = "SELECT id, course, location FROM courses WHERE course LIKE '%Forex%' OR course LIKE '&forex%'";
$query2 = mysqli_query($link, $sql2);
while($result2 = mysqli_fetch_assoc($query2)){
//The problem I am having is here :/
echo "<select id='Forex' name='Forex' style='display: none'>";
echo "<option value='oko'>.$result[1].</option>";
echo "</select>";
print_r($result2);echo '</br>';
}
}else{
$sql = "SELECT id, course, location FROM courses WHERE course LIKE '%Binary%' OR course LIKE '%binary%'";
$query = mysqli_query($link, $sql);
while($result = mysqli_fetch_assoc($query)){
print_r($result);echo '</br>';
}
}
}
Try this code:
$query2 = mysqli_query($link, $sql2);
echo "<select id='Forex' name='Forex' style='display: none'>";
while($result2 = mysqli_fetch_assoc($query2)){
echo "<option value='oko'>{$result['course']}</option>";
}
echo "</select>";
echo '</br>';
From the top in your php:
// not seeing uses of the $form I removed it from my answer
if(isset($_POST['workshop'])){
$workshop = $_POST['workshop'];
$lowerWorkshop = strtolower($workshop);
// neither of $_POST['Forex'] nor $_POST['Binary'] are defined in your POST. you could as well remove those lines?
//Retrieve Binary Workshops HERE we can define the sql in a single line:
$sql = "SELECT id, course, location FROM courses WHERE course LIKE '%$workshop%' OR course LIKE '&$lowerWorkhop%'";
$query = mysqli_query($link, $sql); // here no need to have two results
// Here lets build our select first, we'll echo it later.
$select = '<select id="$workshop" name="$workshop" style="display: none">';
while($result = mysqli_fetch_assoc($query)){
$select.= '<option value="' . $result['id'] . '">' . $result['course'] . '</option>';
// here I replaced the outer containing quotes around the html by single quotes.
// since you use _fetch_assoc the resulting array will have stroing keys.
// to retrieve them, you have to use quotes around the key, hence the change
}
$select.= '</select>';
}
echo $vSelect;
this will output a select containing one option for each row returned by either of the queries. by the way this particular exemple won't echo anything on screen (since your select display's set to none). but see the source code to retrieve the exemple.
I'm attempting to populate an HTML dropdown menu with the results of a MySQL query. The query is running fine and not throwing any errors, but for some odd reason the results won't display correctly.
<?php
$query = "SELECT * FROM parts WHERE itemName LIKE 'Processors:%'";
$result = mysql_query($query) or die("Unable to query CPU parts");
while($row=mysql_fetch_array($result)) {
$option .= "<option value='{$row['itemName']}'></option>";
}
?>
<select name="cpu"><? echo $option; ?></select>
I'm pretty sure it lies somewhere in the $option .= ... ; but it I can't seem to figure it out.
You are not printing the value to be shown in dropdown
try this
while($row=mysql_fetch_array($result)) {
$option .= "<option value='{$row['itemName']}'>{$row['itemName']}</option>";
}
I saw that you are using short tags here
<select name="cpu"><? echo $option; ?></select>
please make sure you have short tag enabled in php.ini
Two things:
You need to initialize $option and print the value to be shown in the dropdown
<?php
$query = "SELECT * FROM parts WHERE itemName LIKE 'Processors:%'";
$result = mysql_query($query) or die("Unable to query CPU parts");
$option = "";
while($row=mysql_fetch_array($result)) {
$option .= "<option value='{$row['itemName']}'>{$row['itemName']}</option>";
}
?>
<select name="cpu"><? echo $option; ?></select>
Seems you forget to add a value inside <option></option> field you only set value for fetching $_POST[] but not for viewing. :D
Also seeing $option variable to be concatenated seems that you already declared it at first
if not you need to probably declared it first.cause this may result to error undefined variable.
<?php
$query = "SELECT * FROM parts WHERE itemName LIKE 'Processors:%'";
$result = mysql_query($query) or die("Unable to query CPU parts");
$option = '';
while($row=mysql_fetch_array($result)) {
$option .= '<option value='.$row['itemName'].'>'. $row['itemName'].'</option>';
}
?>
<select name="cpu"><?php echo $option; ?></select>
Forgot the simplest part:
$aa .= "{$row['itemName']}";
I needed to add the actual label to be displayed between the option tags :)
I've got a database of regions for sale and I'm displaying it in a table for admins to edit the cost, whether it's for sale and who's selling it (seller). For the seller I've got a drop down list with an first option as the current owner for ease of use and then under that I just want it to list the rest of the possible users that could be sellers.
Thing is, there's a good 200 regions and I don't want to loop through every user for each region to display them in a list. Is there a way I can prepare the many 's rather than loop every time. Something like preparing the list as a string then inserting it as HTML? Wouldn't know how to do it that way if possibe.
Thanks in advance.[
let's say you make your list this way:
$str = "<select>";
$result = mysql_query("select * from sellers");
while($row=mysql_fetch_assoc($result)){
$str.= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
$str.="";
And you just output that everywhere you want the list to appear.
Also, you don't have to put the one you want selected by default at the top, you can also add the word 'selected' to the option tag like so:
<option value='1' selected>John Doe</option>
If I understand the question correctly. You need to create an array of option tags.
$Name = array();
$q = "SELECT name FROM users";
$r = mysqli_query ($dbc, $q) or die("Error: ".mysqli_error($dbc));
while($row = mysqli_fetch_array($r)){
$Name[] = "<option value='$row[\"name\"]'>$row[\"name\"]</option>";
}
Then anytime you need that you just loop through array like so:
<select id='thisselect' name='thisselect'>
<?php
foreach($Name as $key =>$line){
echo "$line";
}
?>
</select>
All the answers are good but I suggest you to separate the logic from the content itself, instead of doing all that with concatenated strings, you should do it like this:
<select id="region" name="region">
<?php foreach($regions as $key => $region) ?>
<option value="<?php echo $key ?>"><?php echo $region ?></option>
<?php endforeach; ?>
</select>
Afternoon all,
A very quick question... a friend has set up a form for me using mysql_query. Since he wrote this, I have added an extra column into the database, which I want to pull through into the form.
However I can't seem to get this extra column to appear (labelled Currency). The reason I need it is the query below will pulls back a value and the £ symbol. Because I want to display not only £, but also € prices, I need this extra column to pull through (obviously I will have to remove the £ from the echo below too).
I've tried adding the extra column (Currency) to the code, e.g. "SELECT Room, Currency, Price FROM Spa_Upgrades
but this hasn't worked.
The code is:
<?php
if (isset($id))
{
$query2 = mysql_query("SELECT Room, Price FROM Spa_Upgrades WHERE Spa_Upgrades.Spa_Id = '".$id."' AND Spa_Upgrades.Id = '".$pack."' order by Spa_Upgrades.Order");
$rows = mysql_num_rows($query2);
if($rows==0) {echo "disabled='disabled'/>";}
else
{
echo "/>";
echo "<option value='Default'>Please Select</option>";
for($i=0; $i<$rows; $i++)
{
$result2 = mysql_fetch_array($query2);
echo "<option value='".$result2[0]." £".$result2[1]."pp'>$result2[0] £$result2[1]pp</option>";
}
}
}
Hugely grateful if someone can solve this!
Thanks,
Motley
Alter the query as follows:
SELECT Room, Price, Currency FROM Spa_Upgrades ...
Alter the line beginning echo inside the for loop: replace £ with $result2[2] wherever it appears. (Or if the Currency column doesn't contain the HTML entity for the currency symbol, then replace £ with appropriate code to obtain the symbol from the Currency column entry.)
You also need to add the column to the output... I would also switch to an associative array otherwise if you add a column and its not at the end you have to change all the indexes.
if (isset($id))
{
$query2 = mysql_query("SELECT Room, Price, Currency FROM Spa_Upgrades WHERE Spa_Upgrades.Spa_Id = '".$id."' AND Spa_Upgrades.Id = '".$pack."' order by Spa_Upgrades.Order");
$rows = mysql_num_rows($query2);
if($rows==0) {echo "disabled='disabled'/>";}
else
{
echo "/>";
echo "<option value='Default'>Please Select</option>";
for($i=0; $i<$rows; $i++)
{
$result2 = mysql_fetch_assoc($query2);
$value = $result2['Room'] . ' ' . $result2['Currency'].$result2['Price'].'pp';
echo sprintf('<option value="%s">%s</option>', $value, $value);
}
}
}
Use mysql_fetch_assoc() instead of mysql_fetch_array()
A good practice as well is to separate data retrieving from display logic
Try this:
<?php
$results = array();
if (isset($id))
{
$resource = mysql_query("SELECT room, currency, price FROM Spa_Upgrades
WHERE Spa_Upgrades.Spa_Id = '".intval($id)."' AND Spa_Upgrades.Id = '".intval($pack)."'
order by Spa_Upgrades.Order");
while($row = mysql_fetch_assoc($resource))
$results[] = $row;
}
?>
<select name="..." <?php echo (count($results) > 0 ? '' : 'disabled') ?>>
<option value="Default">Please Select</option>
<?php
foreach($results as $result)
{
$value = $result['room'].' '.$result['currency'].$result['price'].'pp';
echo '<option value="'.htmlspecialchars($value).'">'.htmlspecialchars($value).'</option>'."\n";
}
?>
</select>