I think I am nearly there with this problem, but I can't quite see why my solution isn't working. I'm trying to pre-select an item from a php drop down list that uses a MySQL table. The drop down list populates as expected, but the pre-select doesn't work. My code:
echo $Trans1E; // Display Existing value
echo '<p>Trans1: ';
$q = "SELECT TR1_Name FROM sb_TR1 ORDER BY TR1_Name";
$r = #mysqli_query ($dbc, $q);
$row = mysqli_fetch_array ($r, MYSQLI_NUM);
echo "<select name='Trans1' value=''>Trans1</option>"; // list box select command
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{//Array of records stored in $row
$selected='';
if($row[TR1_Name]==$Trans1E) //determine if the row value is the same as the Existing
{//if it it then mark as selected
echo "<option value=$row[TR1_Name] selected='selected'>$row[TR1_Name]</option>";
}
else
{// if it is not then just inlcude it in the drop down list
echo "<option value=$row[TR1_Name] >$row[TR1_Name]</option>";
}
}
echo "</select>";// Closing of list box
echo '
</p>';
I've seen similar things on this forum for drop down lists which I've incorporated in my code or at least experimented with but without success, I suspect an error in: if($row[TR1_Name]==$Trans1E), but have run out of thinsg to try.
It seems I was closer to the correct code than I thought, I resolved the problem by adding the line:
$Trans1E=mysqli_real_escape_string($dbc, trim(htmlentities($Trans1E)));
before the code.
Despite displaying the content of Trans1E, it seems there was an unwanted element in it, which I hadn't spotted so I thought the code further down was at fault.
Thanks for you comments. Hope this helps others.
Related
I'm trying to create a select box full of options based on data from an array that is built from an sql query, I've tried researching where I'm going wrong but the closest I've managed to get is echoing alot of empty option boxes my code is as follows:
$result = mysqli_query($cons,"SELECT user_name FROM users");
while($row = mysqli_fetch_array($result)){
foreach($row as $key => $value){
echo '<option value="'.$value.'"</option>';}}
If anybody could point me in the right direction that would be great.
EDIT: I can't believe it was something as simple as that! Thank you very much.
On a separate note It's actually giving all of the data twice.
I'll mark as correct answer as soon as I can.
echo '<option value="'.$value.'">'.$value.'</option>';
or
echo "<option value=\"{$value}\">{$value}</option>";
You never closed the opening option tag. If you view your source you'll see it's wonky.
BTW, You don't need the value="" part if you're using the same value in the text of the option.
echo "<option>{$value}</option>";
Entire code as I would do it
$result = mysqli_query($cons,"SELECT user_id, user_name FROM users");
while($row = mysqli_fetch_assoc($result)){
echo "<option value=\"{$row['user_id']}\">{$row['user_name']}</option>";
}
I am trying to print the selected dropdwon item. I have already written the code for dropdown to fetch a column from database.
Now i should print the only the id of selcted dropdown item. i don't know how to make it. please help me, this is my code
<?
$query_name="SELECT id_cat,name FROM `fs01_metier_cat` ORDER BY `fs01_metier_cat`.`name` ASC";
$result = mysql_query ($query_name);
echo "<select name=category value=''></option>";
while($nt=mysql_fetch_array($result))
{
echo "<option value=$nt[name]>$nt[name]</option>";
}
echo "</select>";
$query_id="SELECT id_cat FROM `fs01_metier_cat`";
$result1 = mysql_query ($query_id);
while($row = mysql_fetch_assoc($result1))
{
echo $row['id_cat'];
}
?>
try this:
while($nt=mysql_fetch_array($result)){
echo "<option value='{$nt['id_cat']}'>{$nt['name']}</option>";
}
with {} php can insert also array values into a string and you should set ' ' around the attribute "value"'s value (alot of values here.. ^^), that the html is w3c conform (i dont know if a browser would take it as correct without them..)
without the { } it would look like that:
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['id_cat']."'>".$nt['name']."</option>";
}
depending on your editor code highlighting might work better in the second case ;)
and about the selected item:
i would suggest you to use jQuery to get the content of the selected item
var selectedId = $('#yourselectid option:selected').attr('value');
and then you can e.g. write it to the document or to a div:
document.write(selectedId);
or
$('#yourDivIdWhereYouWantToPutTheSelectedId').html(selectedId);
important: please note that i changed the value's index to id_cat because then you can handle the options with their id
Since the selected option changes everytime you change the dropdown selection, you can not handle this via php. There are ways to do that without a huge library like jQuery (since they are also just simple Javascript) but they simplify such things alot ;)
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 an odd problem. Basicly my page works fine however after a small bit of php, everything after those lines dont load too the page.
<?php
//GET SCHOOLS
$sql = "SELECT `id` FROM `school`";
$query = mysql_query($sql) or die(mysql_error());
$numschools = mysql_num_rows($query);
echo "<select id=\"schoolselect\" class=\"schoolselect\" value=\"Select School\">
<option id='selectschool' value = \"select\" name=\"select\">Select A School</option>
";
while($result = mysql_fetch_array($query) or die(mysql_error()))
{
$school = $result['id'];
echo "<option value = \"$school\" name=\"$school\">".$school ."</option>";
}
echo "</select>";
?>
everything before that works, the php part works but anything after that echo "select" doesnt
any help would be amazing
Never call die(mysql_error()) inside a fetch loop. mysql_fetch_array() returns FALSE when no more rows are available, so when the last row is reached, die() is called and your script will terminate leaving the </select> unclosed. You won't get an error message, but you'll be left with incomplete HTML that won't render properly in the browser.
// Don't call die(mysql_error()) in a fetch loop!
while($result = mysql_fetch_array($query))
{
$school = $result['id'];
echo "<option value = \"$school\" name=\"$school\">".$school ."</option>";
}
Chances are your script is or die()ing inside the <select> tag, which is invisible in the browser.
View the page's source, and you'll most likely see a PHP fatal error or a die message at the end.
EDIT: Or read Michael's answer, cuz I forgot how things worked. Duh :p At least this answer will help you find related problems in the future.