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.
Related
I want to get selected values (of which multiple selections are possible) from my database generated dropdown menu and store those into a PhP variable. I then wish to display the content of that variable into a simple div element below.
This is my code so far which results in nothing inside my simple div:
<form id="menu1" method="POST">
<h2>Area Code</h2>
<select id="multi-select1" name="multi_select1" multiple="multiple">
<?php
//The query asking from our database
$areaCodeSQL = "SELECT ac.Number AS `AreaCode`, ac.Name AS `AreaName`
FROM `AreaCodes` ac"; //SQL query: From the table 'AreaCodes' select 'Number' and put into 'AreaCode', select Name and put into 'AreaName'
$areaCodeResults = $conn->query($areaCodeSQL); // put results of SQL query into this variable
if ($areaCodeResults->num_rows > 0) { // if num_rows(from $results) is greater than 0, then do this:
// output data of each row
foreach($areaCodeResults as $areaCodeResult) //for each item in $areCodeResults do this:
{
$areaNameAndCode = $areaCodeResult['AreaCode'] ." ". $areaCodeResult['AreaName']; //get AreaCode and AreaName from query result and concat them
$areaName = $areaCodeResult['AreaName']; // get AreaName
$areaCode = $areaCodeResult['AreaCode']; //get AreaCode
?><option class="menuoption1" name="menuAreaCode" value="<?php echo $areaCode ?>" ><?php echo $areaNameAndCode; ?></option><?php //Create this option element populated with query result variables
}
}
$result = $_POST['multi_select1'];
?>
</select>
</form>
<div id="showResults1"><?php echo $result ?></div>
Looking around online suggests I might need to use AJAX and jQuery but my tutor buddy insists this can be done within this one script. But I have no idea why my attempt does not work, can some one point me in the right direction???? :-)
Hello i am new to php and i have tried to find a piece of code that i can use to complete the task i need, i currently have a page with a form set out to view the criteria of a course. also i have a dropdown menu which currently holds all the course codes for the modules i have stored in a database. my problem is when i select a course code i wish to populate the fields in my form to show all the information about the course selected. The code i am trying to get to work is as follows:
<?php
session_start();
?>
<? include ("dbcon.php") ?>
<?php
if(!isset($_GET['coursecode'])){
$Var ='%';
}
else
{
if($_GET['coursecode'] == "ALL"){
$Var = '%';
} else {
$Var = $_GET['coursecode'];
}
}
echo "<form action=\"newq4.php\" method=\"GET\">
<table border=0 cellpadding=5 align=left><tr><td><b>Coursecode</b><br>";
$res=mysql_query("SELECT * FROM module GROUP BY mId");
if(mysql_num_rows($res)==0){
echo "there is no data in table..";
} else
{
echo "<select name=\"coursecode\" id=\"coursecode\"><option value=\"ALL\"> ALL </option>";
for($i=0;$i<mysql_num_rows($res);$i++)
{
$row=mysql_fetch_assoc($res);
echo"<option value=$row[coursecode]";
if($Var==$row[coursecode])
echo " selected";
echo ">$row[coursecode]</option>";
}
echo "</select>";
}
echo "</td><td align=\"left\"><input type=\"submit\" value=\"SELECT\" />
</td></tr></table></form><br>";
$query = "SELECT * FROM module WHERE coursecode LIKE '$Var' ";
$result = mysql_query($query) or die("Error: " . mysql_error());
if(mysql_num_rows($result) == 0){
echo("No modules match your currently selected coursecode. Please try another coursecode!");
} ELSE {
Coursecode: echo $row['coursecode'];
Module: echo $row['mName'];
echo $row['mCredits'];
echo $row['TotalContactHours'];
echo $row['mdescription'];
echo $row['Syllabus'];
}
?>
however i can only seem to get the last entry from my database any help to fix this problem or a better way of coding this so it works would be grateful
Thanks
The main error is in your final query, you're not actually fetching anything from the query, so you're just displaying the LAST row you fetched in the first query.
Some tips:
1) Don't use a for() loop to fetch results from a query result. While loops are far more concise:
$result = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
...
}
2) Add another one of these while loops to your final query, since it's just being executed, but not fetched.
For me i would use some javascript(NOTE: i prefer jQuery)
An easy technique would be to do this(going on the assumption that when creating the drop downs, your record also contains the description):
Apart from creating your dropdown options like this <option value="...">data</option>, you could add some additional attributes like so:
echo '<option value="'.$row['coursecode'].'" data-desc="'.$row['description'].'">.....</option>
Now you have all your drop down options, next is the javascript part
Let's assume you have included jQuery onto your page; and let's also assume that the description of any selected course is to be displayed in a <div> called description like so:
<div id="course-description"> </div>
<!--style it how you wish -->
With your javascript you could then do this:
$(function(){
$("#id-of-course-drop-down").change(function(){
var desc = $(this).children("option").filter("selected").attr("data-des");
//now you have your description text
$("#course-description").html(desc);
//display the description of the course
}
});
Hope this helps you, even a little
Have fun!
NOTE: At least this is more optimal than having to use AJAX to fecch the description on selection of the option :)
needing some advice.
I am wanting to include 4 drop down lists on a website, which all contain data from different fields in a mysql table.
I then want to be able to press a submit button and display the required data on a webpage.
I am having trouble with knowing what programming language to use and also finding it difficult to find any tutorials. Any help would be greatly appreciated.
Thanks
You mean a HTML dropdown list or just a select dropdown in a form?
If you mean a select dropdown in a form you could do something like this:
<?PHP
$query = mysql_query("SELECT value FROM table ORDER BY value ASC") or die(mysql_error());
$result = mysql_num_rows($result);
// If no results have been found or when table is empty?
if ($result == 0) {
echo 'No results have been found.';
} else {
// Display form
echo '<form name="form" method="post" action="your_result.php">';
echo '<select name="list" id="lists">';
// Fetch results from database and list in the select box
while ($fetch = mysql_fetch_assoc($query)) {
echo '<option id="'.$fetch['value'].'">'.$fetch['value'].'</option>';
}
echo '</select>';
echo '</form>';
}
?>
And then in your_result.php you should fetch the data from your MySQL database based on value from the (when you fetch use mysql_real_escape_string):
<?PHP $_POST['list']; ?>
You could also do everything in just one file, but thats up to you. Try to use google, there are dozens of tutorials out there.
I have dropdown list that gets values form array based on a mySQL SELECT query. Everything is working fine except that I would like to add the option to select ALL values in the list. Here is my code...
$dataArray = array();
$result = mysql_query("SELECT id, user_name FROM apsc_customers");
while($row = mysql_fetch_assoc($result)) {
$dataArray[$row['id']] = $row['user_name'];
}
AND
if($this->customer_id == ""){
$this->arrFilteringFields[_CUSTOMER] = array("table"=>DB_PREFIX."customers", "field"=>"id", "type"=>"dropdownlist", "source"=>$dataArray, "sign"=>"like%", "width"=>"");
}
Looking forward to any replies.
Thx
Where is your dropdown list? I can't see it in your code. Do you mean html element select created by PHP and based on data from MySQL table? Then you need to use javascript code to select all options in such dropdown list. What is $this in your code? Provide more information, more code and more clarificatios.
Do you mean:
<select>
<?php
while($row = mysql_fetch_assoc($result)) {
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['user_name']; ?></option>
<?php } ?>
</select>
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>