selectbox with multiple columns from mysql database - php

I have the following php code and it's working great for showing 1 column, but I need it to show the values of 10 columns.
<select size="1" name="domeinnaam">
<?php
include '../config.php';
$sql = "SELECT * FROM megabase";
$resultaat = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_array($resultaat))
{
echo '<option>' . $row['domeinnaam1'] . '</option>';
}
?>
</select>
I have tried to add a 2nd echo, but that corrupted the code. I also tried to
echo '<option>' . $row['domeinnaam1'] . $row['domeinnaam2'] . '</option>';
but that didnt work. because the result will then display as follows:
domain1
domain1
domain1domain2
and it should be
domain1
domain1
domain1
domain2
What will work?

Assuming you want each domain name to appear as an option in the select and the domain name fields in your db are domeinnaam1, domeinnaam2, domeinnaam3, etc., you would do the following...
<?php
include '../config.php';
$sql = "SELECT * FROM megabase";
$resultaat = mysql_query($sql) or die (mysql_error());
$domains = array();
while ($row = mysql_fetch_array($resultaat))
{
if (!empty($row['domeinnaam1'])) $domains[] = $row['domeinnaam1'];
if (!empty($row['domeinnaam2'])) $domains[] = $row['domeinnaam2'];
}
?>
<select size="1" name="domeinnaam">
<?php
foreach ($domains as $domain)
{
echo "<option>$domain</option>";
}
?>
</select>
You should use PDO instead of mysql_ functions or the ADODB library works well. mysql_ functions are deprecated as of PHP 5.5
refer to http://www.php.net/manual/en/pdo.construct.php for PDO reference

Your code should not have major PHP configurations or initializations like this. I does not look smart. Tidy it up.
<select size="1" name="domeinnaam">
<?php
include '../config.php';
$sql = "SELECT * FROM megabase";
$resultaat = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_array($resultaat))
{
echo '<option>' . $row['domeinnaam1'] . '</option>';
}
?>
</select>
<?php
include '../config.php';
$sql = "SELECT * FROM megabase";
$resultaat = mysqli_query($conn, $sql) or die ($conn->mysqli_error());
?>
<select size="1" name="domeinnaam">
<?php
while ($row = mysqli_fetch_array($conn, $resultaat))
{
echo '<option>' . $row['domeinnaam1'] . '</option>';
}
?>
</select>
Next don't really try to break options, you could use javascript frameworks like JQuery to achieve a more stylish select. I don't really think you can do this:
while ($row = mysqli_fetch_array($conn, $resultaat))
{
echo '<option>' . $row['domeinnaam1'] . '<br />' .$row['domeinnaam2']. '</option>';
}
Using JQuery, you could a list item in a div:
<ul>
while ($row = mysqli_fetch_array($conn, $resultaat))
{
echo '<li>' . $row['domeinnaam1'] . '<br />' .$row['domeinnaam2']. '</li>';
}
</ul>
Then pass the selected item to a hidden field for later use using the onclick event.
If you want to display the 10 columns in one loop as separate options, this could do it.
while ($row = mysqli_fetch_array($conn, $resultaat))
{
echo '<option>' . $row['domeinnaam1'] .'</option>';
echo '<option>' . $row['domeinnaam2'] .'</option>';
echo '<option>' . $row['domeinnaam3'] .'</option>';
echo '<option>' . $row['domeinnaam4'] .'</option>';
echo '<option>' . $row['domeinnaam5'] .'</option>';
echo '<option>' . $row['domeinnaam6'] .'</option>';
echo '<option>' . $row['domeinnaam7'] .'</option>';
echo '<option>' . $row['domeinnaam8'] .'</option>';
echo '<option>' . $row['domeinnaam9'] .'</option>';
echo '<option>' . $row['domeinnaam10'] .'</option>';
}
I wonder where this would be useful and how. Anything can happen in programming. :)

Related

Populate drop down list from mysql in in php html

I am using the below code to populate drop down list in php html,
<?php
$mid="mario";
$sql = "SELECT * FROM tbl_prdy WHERE col_master_id = '$mid'";
$result = mysqli_query($conn,$sql);
echo "<select name='list'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['col_of_fa'] . "'>" . $row['col_of_fa'] . "
</option>";
}
echo "</select>";
?>
But, I am getting internal server error. I have debugged the code and found that the issue is with the following 2 lines in the above code. There is not much information in server logs. Can you tell me what might be the issue with the following 2 lines of code?
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['col_of_fa'] . "'>" . $row['col_of_fa'] .
"/option>";
}
mixing mysqli with mysql
change
$row = mysql_fetch_array($result)
to
$row = mysqli_fetch_array($result)
You would use this
while($row=mysqli_fetch_assoc($result )){
}
or
while($row=mysqli_fetch_array($result )){
}
//Try this :
while ($row = mysqli_fetch_array($result)) { ?>
<option value="<?php echo $row['col_of_fa'] ?>" ><?php echo $row['col_of_fa'] ?>
</option>
<?php }

Getting duplicate values from mysql_fetch_assoc in while

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>';
}

Show all tables from database into select form in php

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 .

PHP: select current option

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>";
}

Find previously selected option in while loop

I'm trying to get a drop down menu to keep its selected value when the user hits submit, but it fails due to errors on the form.
I have a while loop returning values from a database to build the options for the drop down, but how do I echo "selected" on the right option?
I have tried if($district == $row["name"]) { echo "selected";} as you see below, but it doesn't work.
<?php
$result = mysql_query("SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = 6 GROUP BY dist.id ORDER BY dist.id ASC", $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo '<option value="{$row["name"]}"'; if($district == $row["name"]) { echo "selected";} ; echo '>' . $row["name"] . "</option>";
}
?>
Sorry for the delay. None of the suggested answers worked for me. Any other ideas?
Can you try this,
<?php
$result = mysql_query("SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = 6 GROUP BY dist.id ORDER BY dist.id ASC", $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
$district = $_REQUEST['name']; // You need pass the value you have been submitted
while ($row = mysql_fetch_array($result)) {
$selected ="";
if(trim($district) == trim($row["name"])) { $selected = "selected";}
echo '<option value="{$row["name"]}" '.$selected.' >' . $row["name"] . "</option>";
}
?>
Try this..
if($district == $row["name"])
{
echo "<option value='$district' selected>$district</option>";
}
I just found the answer. This is what I did:
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row["name"] . '"';
if($row["name"] == $district) { echo 'selected';} ;
echo '>' . $row["name"] . '</option>';
}
It seems to have been this line
echo '<option value="{$row["name"]}"';
that was causing the problem.

Categories