Show all tables from database into select form in php - 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 .

Related

Build Combobox with Item Selected

Trying to create a combo box with the user's current value selected. I'm thinking my issue is with the apostrophe's and quotes - can anyone with a sharp eye help? Variable $MCI is created before any quotes/apostrophes and is functioning properly.
$MCI = '';
$MCI = $row['MobileCarrierID'];
echo '
<select name="MobileCarrierName">
<?php
$sql = mysqli_query("SELECT MobileCarrierID, MobileCarrierName FROM tblMobileCarrier ORDER BY MobileCarrierName;");
while ($row = mysqli_fetch_array($sql)){
$MCISelected = (' . $MCI . '==$row["MobileCarrierID"] ? " selected" : "");
echo "<option value=" . $row['MobileCarrierID'] . $MCISelected . ">" . $row['MobileCarrierName'] . "</option>";
}
?>
</select>';
Thank you!
You have
echo '
<select name="MobileCarrierName">
<?php
$sql=
which needs to be changed to
echo '<select name="MobileCarrierName">';
$sql=
Also
$MCISelected = (' . $MCI . '==$row["MobileCarrierID"] ? " selected" : "");
needs to be changed to
$MCISelected = ($MCI==$row["MobileCarrierID"])? " selected" : "";
And your mysqli_query is missing the database connection ie
mysqli_query($db,$query);
Finally, close off with
echo '</select>';
Your quotes and brackets are off and you've placed your selected variable inside your value in the option, a complete edited code should look something like...
<?php
echo '<select name="MobileCarrierName">';
$sql = mysqli_query($conn, "SELECT MobileCarrierID, MobileCarrierName FROM tblMobileCarrier ORDER BY MobileCarrierName;");
while ($row = mysqli_fetch_array($sql)){
$MCISelected = ($MCI==$row["MobileCarrierID"])? " selected" : "";
echo '<option '.$MCIselected.' value="'.$row["MobileCarrierID"].'">'.$row["MobileCarrierName"].'</option>';
}
echo'</select>';
Check out How to set an option from multiple options or array with different values to views as selected in select box using PHP for a guide on how it works
<?php
$sql = mysqli_query("SELECT MobileCarrierID, MobileCarrierName FROM tblMobileCarrier ORDER BY MobileCarrierName;");
?>
<select name="MobileCarrierName">
<?php
while ($row = mysqli_fetch_array($sql)){
$MCI = $row['MobileCarrierID'];
$MCISelected = ($MCI==$row["MobileCarrierID"]) ? " selected" : "";
echo "<option value=".$MCI." ".$MCISelected.">".$row['MobileCarrierName']."</option>";
}
?>
</select>
try this one

Variable drop down menu in php

I want to have a dropdown menu with as many options as a number in my database.
This is what i have but doesnt work:
<?php
// set the pointer back to the beginning
mysqli_data_seek($result, 0);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo '<div class="w-clearfix">
<div class="price">' .$row['Price']. '€</div>
//some code
<select class="w-select selectorplatos" id="numeroplatos" name="numeroplatos" data-name="numeroplatos">';
$capacity= "SELECT Capacity FROM Meals WHERE Meal_ID = '".$meal."';";
$resultcap = mysqli_query($conn, $capacity) or die("Couldn't execute query. ". mysqli_error($conn));
$i = 1;
// output data of each row
while($row1 = $resultcap->fetch_assoc()) {
echo '<option value="' .$i. '">' .$i. "</option>";
$i = $i+1;
}
echo '</select>
<input class="w-button pedirya" type="submit" value="¡Pedir ya!" data-wait="Espera por favor..." wait="Espera por favor...">
</form>
// more code here
mysqli_close($conn);
?>
Any clue whats wrong?
The command to display the drop down list cannot be executed.
Cheers!
Try changing your code to this:
echo '<select class="w-select selectorplatos" id="numeroplatos" name="numeroplatos" data-name="numeroplatos">';
$capacity = "SELECT Capacity FROM Meals WHERE Meal_ID = '".$meal."';";
$resultcap = mysqli_query($conn, $capacity) or die("Couldn't execute query. ". mysqli_error($connection));
$i = 1;
while($i < $resultcap) {
echo '<option value="' .$i. '">' .$i. '</option>';
$i = $i+1;
};
echo '</select>';
You weren't properly concatenating you MySQL query. It's also good practice to add or die("Couldn't execute query. ". mysqli_error($connection)) to get feedback on what went wrong when executing your query.
I also added echo because, assuming all of this is wrapped inside <?php ?> tags, well you need to echo HTML.
Please try this. I have tested it:
<select class="w-select selectorplatos" id="numeroplatos" name="numeroplatos" data-name="numeroplatos">'
<?php
$sql = "SELECT Capacity FROM meals";
$result = $conn->query($sql);
$i = 1;
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option value="' .$i. '">' .$i. "</option>";
$i = $i+1;
}
?>
</select>
Ok after a lot of research and inspiration from comments, i got it working the following way:
<?php
mysqli_data_seek($result, 0);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo '<div class="w-clearfix">
<div class="price">' .$row['Price']. '€</div>
<div class="priceindic">Precio por plato</div>
<div class="w-form numplatosselect">
<form class="w-clearfix" id="numerodeplatos" name="numerodeplatos" data-name="numerodeplatos" action="https://rest.nexmo.com/sms/json?api_key='
<label class="labelselector" for="numeroplatos-2">Numero de platos:</label>
<select class="w-select selectorplatos" id="numeroplatos" name="numeroplatos" data-name="numeroplatos">';
for ($i = 1; $i <= $row['Capacity']; $i++) {
echo '<option value="' .$i. '">' .$i. "</option>";
}
?>
a simple for loop does the trick using fetch_assoc from above and including Capacity in the original query

MySQL Select based on drop down value

I have the following code:
<?php
session_start();
include_once("config.php");
$query = "SELECT Category FROM books";
$result = mysqli_query ($mysqli, $query);
echo '<select name="dropdown" value=""><option value="">Dropdown</option>';
while($row = mysqli_fetch_array($result))
{
echo '<option value="' . $row['Category'] . '">' . $row['Category'] . '</option>';
}
echo "</select>";
?>
the values of the drop down box are filled from the database.
I was wondering if theres a way to have a select statement that will run when a user clicks on one of the options in the drop down menu and then populate the results in a table?
any information will help!
Thanks
Ok, resontant81, you want to fill a table depending on the option selected, next code does exactly what you want, the explanation comes just after :
<html>
<head>
<title>My list</title>
<script type="text/javascript">
//----------------------------------------------------------------
// SENDS SELECTED OPTION TO RETRIEVE DATA TO FILL TABLE.
function send_option () {
var sel = document.getElementById( "my_select" );
var txt = document.getElementById( "my_option" );
txt.value = sel.options[ sel.selectedIndex ].value;
var frm = document.getElementById( "my_form" );
frm.submit();
}
//----------------------------------------------------------------
</script>
</head>
<body>
Click on any option
<br/>
<select id="my_select" onchange="send_option();">
<option>Select an option</option>
<?php
//----------------------------------------------------------------
// LIST FILLED FROM DATABASE (ALLEGEDLY).
for ( $i = 0; $i < 5; $i++ )
{ $text = chr($i+65) . chr($i+65) . chr($i+65);
echo "<option value='" . $text . "'>" . $text . "</option>";
}
//----------------------------------------------------------------
?>
</select>
<br/>
<br/>
<table>
<?php
//----------------------------------------------------------------
// TABLE FILLED FROM DATABASE ACCORDING TO SELECTED OPTION.
if ( IsSet( $_POST["my_option"] ) ) // IF USER SELECTED ANY OPTION.
for ( $i = 0; $i < 4; $i++ ) // DISPLAY ROWS.
{ echo "<tr>";
for ( $j = 0; $j < 6; $j++ ) // DISPLAY COLUMNS.
echo "<td>" . $_POST["my_option"] . "</td>"; // DISPLAY OPTION.
echo "</tr>";
}
else echo "<tr><td>Table empty</td></tr>";
//----------------------------------------------------------------
?>
</table>
<!-- FORM TO SEND THE SELECTED OPTION. -->
<form method="post" action"01.php" style="display:none" id="my_form">
<input type="text" id="my_option" name="my_option"/>
</form>
</body>
</html>
To make things easier for you (and for me), I am not using a database, all you have to do is copy-paste previous code to a text file, rename it "01.php" (because that's the action of the form, you can change it), and run it in your browser, is ready to use.
The dropdown is filled from database (in this case, with letters), when an option is selected the page reloads with the selected option and fills the table.
You said: "a select statement that will run when a user clicks on one of the options in the drop down menu and then populate the results in a table". This select statement you want you must put it right after the line :
if ( IsSet( $_POST["my_option"] ) ) // IF USER SELECTED ANY OPTION.
So your select statement will take the selected option from $_POST and use it to retrieve the right data and display it.
Let me know if it helps you.
This is the code to fill the dropdown, it's my code with yours combined:
// LIST FILLED FROM DATABASE (ALLEGEDLY).
$query = "SELECT Category FROM books";
$result = mysqli_query ($mysqli, $query);
while ( $row = mysqli_fetch_array($result) )
echo "<option value='" . $row['Category'] . "'>" . $row['Category'] . "</option>";
Next edit is to fill the table. Change the query for the right one if it's not right :
// TABLE FILLED FROM DATABASE ACCORDING TO SELECTED OPTION.
$query = "SELECT Category FROM books where category like '" . $_POST["my_option"] . "'";
$result = mysqli_query ($mysqli, $query);
while( $row = mysqli_fetch_array($result) )
echo "<tr>" .
"<td>" . $row['book_name'] . "</td>" .
"<td>" . $row['author'] . "</td>" .
"<td>" . $row['Category'] . "</td>" .
"</tr>";
I'm assuming $mysqli is your db connection and it's made through config.php. I'm also assuming that category is a column name in the books table. It is up to you to sanitize and validate the user input. This is simply an example to get you started.
page.php ....
<?php
session_start();
include_once("config.php");
function categories() {
global $mysqli;
$result = "";
$stmt = "SELECT Category FROM books GROUP BY Category";
$sql = mysqli_query ($mysqli, $stmt);
while ($row = $sql->fetch_array(MYSQLI_BOTH))
{
$result .= '<option value="' . $row['Category'] . '">' . $row['Category'] . '</option>';
}
mysqli_free_result($sql);
mysqli_close($mysqli);
return $result;
}
IF (isset($_POST['ThisForm'])) {
$category = htmlspecialchars(strip_tags(trim($_post['dropdown'])));
$stmt = "SELECT * FROM books WHERE category ='$category'";
$sql = mysqli_query ($mysqli, $stmt);
while ($row = $sql->fetch_array(MYSQLI_BOTH))
{
// do something with result
}
// free result and close connection
mysqli_free_result($sql);
mysqli_close($mysqli);
}ELSE{
// base form
echo '<form action="page.php" name="something" method="post">';
echo '<select name="dropdown" value=""><option value="">Dropdown</option>'.categories().'</select>';
echo '<input type="submit" name="ThisForm" value="submit" />';
echo '<form>';
}
?>

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

selectbox with multiple columns from mysql database

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. :)

Categories