Display data from database as option in a select - php

I'm coding a website for an online DVD rental and booking system and trying to call into a dropdown menu the DVDID which is the primary key and the title of the DVDs in my phpmyadmin data base but when I try to call the ID in it does not work. Any help would be appreciated.
<form name="FrmAmend" method="post" action="amenddvd2.php">
Select from the list below<br>
<select name="Film" title="Select DVD">
<option value="" selected disabled>Select DVD</option>
<?php
$result = mysqli_query($con, "SELECT `DVDID`, `Title` FROM tbldvd;");
$row = mysqli_fetch_assoc($result);
foreach ($result as $row) {
echo "<option value='" . $row['DVDID'] . $row['Title'] . "'>" . $row['DVDID'] . $row['Title'] . "</option>";
}
?>
</select><br>
<a href="menu.php"</a>Return To Main Menu<br>
<input type="submit" name="Submit" value="Select DVD">
</a>
</form>

The issue you have is the way you collect the data, you have the following;
$row = mysqli_fetch_assoc($result);
foreach ($result as $row) {
mysqli_fetch_assoc collects a single row from the result set, a better way to do this, would be to replace the above and use the following;
while ($row = mysqli_fetch_assoc($result) {
And this will get the results out of the database, row by row and print these without having to have changes inside the loop
Looping in a while, using mysqli_fetch_assoc collects each row, one at a time allowing you to use this more effectively.
So, if you have the following data;
DVDID Title
1 ABC
2 DEF
A while loop collects the rows, one at a time, for each row in your result set, where a single fetch_assoc will collect the first that appears in the result set and nothing more
As an additional, you have the following HTML;
<a href="menu.php"</a>Return To Main Menu<br>
This is not valid as HTML, from this, it looks like you want "*Return To Main Menu" to be the hyperlink, so replacing the above with the following will resolve this issue;
Return To Main Menu<br>
This adds the close to the first "a" (>) and moves the text to within the opener and closer tags

Related

PHP dropdown menu that concatenates 2 rows from MySQL data table

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.

PHP - populate a select drop down from MySQL DB and have that field auto-populated in a form

I am trying to accomplish two things with the code below. Firstly I want my select options to be populated form my database. Secondly I want the field in the form to have the stored value selected on page load (like in a profile for a member). The way I have implemented below works, kind of, but I have two problems. Firstly if you open the dropdown then the selected option appears twice (once at the top and once in its normal position). Secondly if it is a required field then the user has to open the dropdown and select it again, even though it is appearing in the field (horrible ux). If it is not a required field the form acts as if nothing is selected and I get a Undefined index error further down the line. I am very sure there is a better way to implement what I am trying to achieve that wont give me these problems... all help greatly appriciated.
<?php
$query6 = "SELECT catname FROM travisor_catagory";
$result6 = mysqli_query($conn, $query6) or die(mysqli_error($conn));
$queryread3 = "SELECT * FROM travisor_catagory WHERE id = $catagory";
$result3 = mysqli_query($conn, $queryread3) or die(mysqli_error($conn));
if (mysqli_num_rows($result3) > 0) {
while ($row = mysqli_fetch_assoc($result3)) {
$cat = $row["catname"];
}
}
echo "<div class='form-group'>
<label>Catagory *</label>
<select class='form-control' name='catagory' required>
<option disabled selected value> $cat </option>";
if (mysqli_num_rows($result6) > 0) {
while ($row2 = mysqli_fetch_assoc($result6)) {
$catagory2 = $row2["catname"];
echo "<option>$catagory2</option>";
}
}
echo "</select>"
?>
Don't mix things up so much.....
When you get into larger programs, you will get lost really quickly, so K.I.S.S.!!!
You can 'jump' in/out of HTML and back to PHP to echo the $options variable, then back to HTML to complete the select. (this is my description of it when I teach newbies - this concept of 'jump in/out' works for PHP, HTML, JS - well any languages that you can combine in one page... - it is worth grasping the concept!)
First, get the options you will need with ONE query (watch how we take care of the selected one as well) - this will make a 'packet' of data in the $options variable.
<?php
// declare some values that we'll use later
$options = '';
// gather the data for the options
$sql = "SELECT id, catname FROM travisor_catagory";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$selected = '';
if($category == $row['id']){
$selected = "selected";
}
$options .= '<option ' . $selected . ' value="' . $row["id"] . '">" . $row["catname"] . "</option>";
}
}
// now we will 'jump' out of PHP and back to HTML
?>
<!-- we are in HTML, so comments and language changed... -->
<div class='form-group'>
<label>Catagory *</label>
<select class='form-control' name='catagory' required>
<!-- here we 'jump' out of HTML and into PHP to use the $options variable -->
<?php echo $options; // and back out of PHP to HTML... ?>
<!-- where we finish up our select and whatever other HTML things -->
</select>
</div>
That should take care of both your issues with what you had.....
BTW, it looks like you are using Bootstrap - if so, I HIGHLY recommend you check this out (changed my life about fighting with select boxes! :) Bootstrap Select

Displaying form selected option results from database

Okay, I'm reframing this whole question because the earlier version was a bit convoluted.
Here's the scenario:
I have a MySQL table called "churches."
I have a form with four selects. The options are drawn dynamically from the table, so that users can search on four table columns to find churches that fit the criteria (country, state/province, city, presbytery)
I also have working code to get all the table data to display.
What I haven't figured out is how to use the selected option from the form to filter the results.
My current code is below:
<form action="display0506b.php" method="post">
<select name="country">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT country FROM churches");
$query_display = mysqli_query($link,"SELECT * FROM churches");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['country'] . "</option>";
}
?>
</select>
<select name="state">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT state FROM churches WHERE state != ''");
$query_display = mysqli_query($link,"SELECT * FROM churches WHERE state != ''");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['state'] . "</option>";
}
?>
</select>
<input type="submit" value="Go!">
</form>
<?php
if(isset($_POST['country']))
{
$name = $_POST['country'];
$fetch = "SELECT * FROM churches WHERE id = '".$name."'";
$result = mysqli_query($link,$fetch);
echo '<div class="churchdisplay">
<h4>' .$row['churchname'].'</h4>
<p class="detail">' .$row['detail'].'</p>
<p><b>' .$row['city'].'</b>, ' .$row['state'].' ' .$row['country'].'</p>
<p>' .$row['phone'].'</p>
// etc etc
</div>';
}
else{
echo "<p>Please enter a search query</p>";
}
?>
Note that in the form above, I only have two selects for illustration, but ultimately I will have four, as mentioned; and I am only attempting the country selection at this point to keep things simple. Ultimately, I will need the ability to select any (and preferably all) of the four categories.
As you can see, this code does attempt to "grab" the selected value from the form, but it's not working. I've pondered numerous tutorials and examples, but none of them do exactly what I'm after, and as an extreme PHP novice, I'm stumped.
So the question: how do I tweak this so that I can "grab" the form selection and display the relevant results from my table?
Edit: I am using mysqli syntax, and want to just use PHP and MYSQL (no Ajax etc) if possible.
Well, it looks like I've finally found what I needed here:
display result from dropdown menu only when value from it is selected
Or, I should say, I've got it to work with one select option. Still need to see if I can figure out how to get four working together.

Filling an HTML drop down box from database using php, but I'm missing one record

I'm pulling rows from a mysql database to fill a drop down box. It works, but it misses out one option. I think it might be due to the fact I'm using the <optgroup> tag in the middle, where the option would be - in fact if I remove this, the whole list is printed.
My database has data similar to below:
Module Code|Module Name
-----------|-------------
SE1AA11 |Animal Acting
SE1BB11 |Boring Billiards
... | ...
SE2AA11 |Animal Archery
SE2BB11 |Boring Boxes
... | ...
(... indicates more data and yes, the module names are made up)
When the page loads, it misses out the first of the SE2 options. Any ideas why? Any help would be appreciated. Code below:
<select name="module1" id="module1" style="display: none;">
<option value="" selected disabled>Module 1</option>
<?php
$sql = "SELECT * FROM Modules";
$result=mysqli_query($con,$sql);
echo '<optgroup label="Part One">';
while (($row = mysqli_fetch_array($result)) &&
(substr($row['ModuleCode'], 0, -4) == "SE1")){
$code = $row['ModuleCode'];
$name = $row['ModuleName'];
echo '<option value="'.$code.'">' . $name . '</option>';
}
echo '</optgroup>';
echo '<optgroup label="Part Two">';
while (($row = mysqli_fetch_array($result)) &&
(substr($row['ModuleCode'], 0, -4) == "SE2")){
$code = $row['ModuleCode'];
$name = $row['ModuleName'];
echo '<option value="'.$code.'">' . $name . '</option>';
}
echo '</optgroup>';
?>
</select>
You miss out one record because of this: when your first while loop has iterated over all SE1* records, it does another call to mysqli_fetch_array() which fetches the next record from your result set. This record does not comply with your second condition (it does not start with 'SE1') so PHP moves to the next while loop, where another call is made to mysqli_fetch_array() which will fetch the next record from your result set.
Because your first 'SE2*' item was already fetched by the first loop, but never processed by that loop, you will not see that record back in your dropdown list.

select id from the select gender dropdown list

I have a dropdown list of gender. I am getting the values from my table 'candidate' and in this table i have a field which is actually a foreign key to another table.
The field is gender_code_cde, and the table name is gender_code. Now gender_code contains 2 rows. and id and a description. Its structure is like:
1->Male
2->Female
Its being displayed in dropdown list. but I want to get the id 1 if male is selected and id 2 if female is selected. My code is below:
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
I am working in codeIgniter.
// this will alert value of dropdown whenever it will change
<script>
function getvalue(val)
{
alert(val);
}
</script>
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER" id="Gender" onchange="getvalue(this.value)">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
In Javascript, you can get the value with native JS.
var e = document.getElementById("give-the-select-element-an-id");
var gender_cde = e.options[e.selectedIndex].value;
If, you want it back at the server, it will come in to PHP as $_GET['GENDER'] or $_POST['GENDER'] depending on if the form does a POST or a GET request.
If you are submitting a (POST) form and this is inside that form you can access the the value (id) from CodeIgniter's $_POST wrapper: $this->input->post('GENDER');. I don't use CodeIgniter so I could be wrong, but it will be located in your $_POST array from PHP.
If you just want to replicate the variable somewhere on the page you can just echo it. Or set via js/jQuery with document.getElementById('#something').value = value; or jQuery('#something').html(value);.
You should also change the following:
use a foreach in place of your while:
foreach ($query as $row) {
echo $row['gender_x'] . $row['gender_y'];
}
use the CodeIgniter SQL wrapper instead of depreciated PHP functions. The query part is $this->db->query('SELECT statement goes here');. You should look at your CodeIgniters' version documentation for a more in depth explanation.
EDIT: To make it a bit more clear, an example:
$query = $this->db->query('SELECT * FROM gender_code');
foreach ($query->result() as $row) {
echo '<option value="' . $row->gender_cde . '">' . $row->geneder_dsc . '</option>';
}
This is assuming you have setup the previous calls in CodeIgniter. Please see http://ellislab.com/codeigniter/user-guide/database/examples.html and you may wish to read http://ellislab.com/codeigniter/user-guide/

Categories