I have used a dropdown list which is populated with data from a database using a query but i can't seem to add a default value to the top of the list e.g. "Select Class". All DB data is being retrieved fine but cannot add any default title like Select Class.
function query(){
$classes = mysql_query("SELECT * FROM class") or die("Could not search!");
while ($row = mysql_fetch_array($classes)) {
echo '<option value="Select Class"'>' . $row['class_name'] . '</option>';
}
}
All help is much appreciated!
You need to add an <option> before you begin your loop.
function query(){
// This is the line you are missing
echo '<option>Select a class</option>';
$classes = mysql_query("SELECT * FROM class") or die("Could not search!");
while ($row = mysql_fetch_array($classes)) {
echo '<option value="Select Class"'>' . $row['class_name'] . '</option>';
}
}
Just echo out the default option before the while loop starts:
$classes = mysql_query("SELECT * FROM class") or die("Could not search!");
echo '<option value="">Select Class</option>';
while ($row = mysql_fetch_array($classes)) {
echo '<option value="Select Class"'>' . $row["class_name"] . '</option>';
}
Related
I have form with a number of drop boxes which have the numbers 1-5 in them. I can use this code to populate a drop down but was wondering if I can somehow only make the call to the db once but populate all the drop downs that use the same numbers?
<?php
$sql = "SELECT * FROM riskNumDrop";
$result = $conn->query($sql);
if (!$conn->query($sql)) {
echo "query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
echo '<select class="assess" name="precontcons" style="width:4em">' ;
while($row = $result->fetch_assoc()){echo '<option value='. $row['riskNumDrop'] .'>'.$row['riskNumDrop'].'</option>';}
?> </select>
So Ideally, I generate the output once and reuse it multiple times. Im guessing an array (which $result already is) but how do I populate a drop down from it? TIA
Saving as a string would save you the processing of having to loop through the same data generating the same output multiple times. If this is what you want, you could do the following.
Replace:
echo '<select class="assess" name="precontcons" style="width:4em">' ;
while($row = $result->fetch_assoc()){echo '<option value='. $row['riskNumDrop'] .'>'.$row['riskNumDrop'].'</option>';}
?> </select>
with:
$drop = '<select class="assess" name="precontcons" style="width:4em">' ;
while($row = $result->fetch_assoc()){
drop .= '<option value='. $row['riskNumDrop'].'>'.$row['riskNumDrop'].'</option>';
}
$drop .= '</select>';
Then you can echo $drop several times if you want.
If for whatever reason you want different select attributes, you could just save the options list and print the select around that, like this:
$dropOptions = "";
while($row = $result->fetch_assoc()){
$dropOptions .= '<option value='. $row['riskNumDrop'].'>'.$row['riskNumDrop'].'</option>';
}
Then just echo '<select class="foo" name="bar">'.$dropOptions.'</select'>
You could store the data into an array, and then print the data by enumerating the array.
$risks = array();
// Load values into array.
while ($row = $result->fetch_assoc()) {
array_push($row['riskNumDrop']);
}
// Drop down #1
echo '<select>';
foreach ($risks as $risk) {
echo '<option value='. $risk .'>'. $risk .'</option>';
}
echo '</select>';
// Drop down #2
echo '<select>';
foreach ($risks as $risk) {
echo '<option value='. $risk .'>'. $risk .'</option>';
}
echo '</select>';
Simply get the results into an array using the fetch_all method. It returns all rows from the result set into an associative or numeric array. The you can do whatever you want with such array:
$result = $conn->query('SELECT * FROM riskNumDrop');
if (!$result) {
echo "query failed: (" . $mysqli->errno . ") " . $mysqli->error;
exit; // fetch_* functions cannot be called on error (sice $result is false)
}
// get all rows from the result
$rows = $result->fetch_all(MYSQLI_ASSOC);
// output first dropdown...
echo '<select name="dropdown_1">';
foreach ($rows as $row) {
// options for the first dropdown (same as you did before)
}
echo '</select>';
// output second dropdown...
echo '<select name="dropdown_2">';
foreach ($rows as $row) {
// options for the second dropdown
}
echo '</select>';
I'm stuck with while in php this is the part that makes problem and still returning duplicate rows. When I use select in phpmyadmin I get what I'm looking for. I think problem is with while. Can you look at it?
<td><select name='movie_type'>
<?php
$query = 'SELECT movietype_id, movietype_label FROM `movietype`';
$result = mysql_query($query, $db) or die (mysql_error($db));
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $value) {
echo '<option value="' . $row['movietype_id'] . '">';
echo $row['movietype_label'] . '</option>';
}
}
?>
</select></td>
You don't need to use foreach loop, just change your code to:
while ($row = mysql_fetch_assoc($result)){
echo '<option value="' . $row['movietype_id'] . '">';
echo $row['movietype_label'] . '</option>';
}
Hiho,
I have a little problem with showing all table names on page in form .
Code bellow:
<select name="users" onchange="showTables(this.value)">
<option value="">Select a table:</option>';
$result = mysql_list_tables($db_name);
for ($i = 0; $i < count(mysql_num_rows($result)); $i++){
echo '<option value="' . mysql_tablename($result, $i) . '">' . mysql_tablename($result, $i) . '</option>';
}
echo '</select>
</form>
<br>
<div id="tablesDb"><b>All content from selected table will be listed there.</b></div></div>';
I try with mysqli too ,and i get results but still without names of the tables and nothing can be select.
Maybe someone know how to get this work.
First, you definitely want to be using MySQLi, as the MySQL extension is deprecated. Second, you can probably get all of the data you need in a simple SELECT query like this:
select `TABLE_NAME` from information_schema.tables
Try this
$mydbname = 'database_name';
$con=mysqli_connect("localhost","my_user","my_password",$mydbname);
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$options = '';
// for the query you can use two of the following lines (line1+line2 OR line3+line4)
//Use line (line1+line2)
$result = mysqli_query($con,"SHOW TABLES");
$column_name ='Tables_in_'.$mydbname;
// OR (line3+line4
$result = mysqli_query($con,"SELECT TABLE_NAME AS tbl FROM information_schema.tables" WHERE TABLE_SCHEMA = \"'.$mydbname.'\"; ");
$column_name ='tbl';
while($row = mysql_fetch_array($result))
$options .= '<option value="' . $row[$column_name] . '">' . $row[$column_name] . '</option>';
echo '<select name="users" onchange="showTables(this.value)">';
echo '<option value="0">Select a table:</option>';
echo $options;
echo '</select>';
I modify code to this:
<select name="db_tablelist" onchange="showTables(this.value)">
<option value="">Select a table:</option>';
$result = mysqli_query($con,"SHOW TABLES");
while($row = mysqli_fetch_array($result)) { echo '<option value="' . $row[0] . '">'.$row[0].''; } echo '';
echo '</select>
</form>
<br>
<div id="tablesDb"><b>All content from selected table will be listed there.</b></div></div>';
And now everything works .
I have a DB table with all categories (id, category) and table with all of events (id, event, categoryID).
And on the event editing form I have the select field with all of the categories (getting from the DB). But sinse I'm developing an editing form, I need to select current category by default.
This is my select field (PHP method that gets all the categories from DB and puts them in the following order):
<option value="1">Cat1</option>
<option value="2">Cat2</option>
<option value="3">Cat3</option>
<option value="4">Cat4</option>
<option value="5">Cat5</option>
Let's say, current event is under category 3, so I need the following HTML to be generated:
<option value="1">Cat1</option>
<option value="2">Cat2</option>
<option value="3" selected>Cat3</option>
<option value="4">Cat4</option>
<option value="5">Cat5</option>
How do I achieve it with PHP, if I have the catID?
Hopefully, this question is clear enough. Sorry for my bad explanation
UPD: This is my PHP code that generates category list:
public function getCatList($conf) {
$mysqli = $this->dbConnect($conf);
// Quering...
$query = "SELECT * FROM categories";
$result = $mysqli->query($query);
while($row = mysqli_fetch_array($result)) {
echo '<option value="' . $row['id'] . '">' . $row['category'] . '</option>';
}
}
Appending to your while iteration a condition will solve this for you:
while($row = mysqli_fetch_array($result)) {
$isSelected = $row['id'] == $catID;
echo '<option '.($isSelected ? 'selected="selected"' : '').' value="' . $row['id'] . '">' . $row['category'] . '</option>';
}
You're making a comparison if the current value is the same as that stored in $catID - and store the boolean result in a variable. In the echo you're just doing a conditional forking and appending the selected attribute if the value was true, otherwise not appending any empty string.
You can do it like
while($row = mysqli_fetch_array($result)) {3
echo '<option value="' . $row['id'] . '"';
//if condition is met then make the option selected
if($row['categoryID'] == 3) {
echo " selected='selected' ";
}
echo '>' . $row['category'] . '</option>';
}
you should add the selected catID as a parameter to your getCatList-function. Then just change the creation of your HTML to include the selected-attribute:
public function getCatList($conf, $catID = 0) {
$mysqli = $this->dbConnect($conf);
// Quering...
$query = "SELECT * FROM categories";
$result = $mysqli->query($query);
while($row = mysqli_fetch_array($result)) {
echo '<option value="' . $row['id'] . '"' . ($row['id']==$catID?' selected':'') . '>' . $row['category'] . '</option>';
}
}
now you can just pass the catID to your function:
$myConf = "something";
$myCatID = 3;
getCatList($myConf, $myCatID);
//query for the categories and options
$current_value = 3;
$total_num_of_options = mysql_num_rows($your_query_result);
for($count = 1; $count <= $total_num_of_options){
echo "<option value='".$count."' ";
if($count == $current_value)
echo "selected";
echo ">cat".$count."</option>";
}
I'm working on a form that has 4 different select elements from 2 tables of a database. I haven't done anything like this and I don't really know how to do it.
I have a table called "students" from I need "name" and "class" and a table called "books" from I need "writer" "title" ... all is one select element and all has more than 2 option values.
I've tried with only one sql query and one select but it shows only one option on the site, wether it has about 6 values in the database.
My code:
$sql = "SELECT class
FROM students";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$select_class = "<option value={$row['class']}>{$row['class']}</option>";
}
<select id="class" name="class">
<?php print $select_class; ?>
</select>
How would it be correct?
try this
$sql = "SELECT class FROM students";
$result = mysql_query($sql);
echo '<select id="class" name="class">';
while ($row = mysql_fetch_assoc($result)) {
echo "<option value={$row['class']}>{$row['class']}</option>";
}
echo '</select>';
You are overwriting $select_class on each while() loop. You need to concatenate $select_class . Change to $select_class .=
$select_class = "";
while ($row = mysql_fetch_assoc($result)) {
$select_class .= "<option value={$row['class']}>{$row['class']}</option>";
}
Changing this:
$select_class = "<option value={$row['class']}>{$row['class']}</option>";
to this:
$select_class .= "<option value={$row['class']}>{$row['class']}</option>";
might solve your problem.
Right now you are constantly resetting the value of $select_class, instead of adding to it. The .= assignment should help you get around this.
As always, be sure to up-vote any StackOverflow answers you find useful.
Try this
<?php
$dbhandle = mysql_connect($hostname, $username, $password) or die("can't connect");
$table = "students";
$sql = "SELECT * FROM students";
$result = mysql_query($sql, $dbhandle);
mysql_data_seek($result, 0);
?>
<form>
<select class="dropdown" name="dropdown">
<?php
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['class'] . '">' . $row['class'] . '</option>';
}
}
?>
</select>
</form>