I have an edit form with two fields: name and category. The category field is stored in the database as a number. I would like to associate each number (3 in total) to a string in the edit form and display the category recorded in the database and then the other.
<form>
<input type="text" name="name" value="<?php echo $result->name; ?>">
<select name="categoria">
<option value="<?php echo $result->category; ?>">books</option>
<option value="2">cds</option>
<option value="3">dvds</option>
</select>
</form>
I'm not sure if there was a question there, but I think I know what you're trying to do. I don't know what your table structure is like, so this is just an example.
$sql = mysqli_query("SELECT * FROM categories ORDER BY category_title ASC");
while($row = mysqli_fetch_array($sql))
{
$num = $row['category_number'];
$val = $row['category_title'];
echo '<option value="' . $num . '">' . $val . '</option>';
}
That will give you all of the options for your select element, set their value to the number from the database, and display the name of the category for the viewer.
EDIT:
Here's using the MySQLi class, which will save you some time. However, there's not much use in building a class for this particular function. It's so short.
$mysqli = new MySQLi($host, $user, $pass, $database);
$sql = $mysqli->query("SELECT * FROM products ORDER BY category_name ASC");
while($row = $sql->fetch_array())
{
$num = $row['category'];
$val = $row['category_title'];
echo '<option value="' . $num . '">' . $val . '</option>';
}
EDIT 2:
Just use the while() loop, rather than do...while(). It'd go like this:
$dbh = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
$sth = $dbh->query("SELECT * FROM products ORDER BY category_name ASC");
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
$num = $row['category'];
$val = $row['categoty_name'];
echo '<option value="' . $num . '">' . $val . '</option>';
}
Related
So what Ia m trying to do is to call a value from my server and input it in a variable based on what I have chosen from the dropdown box and then I want to take those variables and calculate a new output through javascript (I don't think that I want help for the last part but I like being up-front). Anyway, here is the code
$db_name = 'prod_chrotex_db';
$conn = new mysqli($host, $user, $pass, $db_name);
$query = mysqli_query($conn, "SELECT * FROM table1 INNER JOIN table2 ON id ");
echo '<select name="TITLE">';
while ($row = mysqli_fetch_array($query)) {
echo '<option value="' . $row['title'] . '">' . $row['title'] . '</option>';
$rows = mysqli_fetch_assoc($query);
echo 'ID: ' . $rows['ID'] ;
$value = $rows['values']
};
echo "</select>";
$db_name = 'prod_chrotex_db';
$conn = new mysqli($host, $user, $pass, $db_name);
$query = mysqli_query($conn, "SELECT * FROM table1 INNER JOIN table2 ON id ");
echo '<select name="TITLE" id="selectb" onchange="callfunction();>';
while ($row = mysqli_fetch_array($query)) {
echo '<option value="' . $rows['ID'] . '" ">' . $row['title'] . '</option>';
};
echo "</select>";
?>
<script>
function callfunction(){
var val = document.getElementById('selectb').value();
// You get the selected value in val variable. Here you can calculate what you want
}
</script>
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>';
}
?>
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 am trying to figure out how to mark a dropdown option as selected by checking it's value, but the value is coming from another query.
I get the $FK_TopicID from the query called $quickedit. The dropdown list is generated by a different query called $topresult. I have an IF/ELSE statement that is supposed to print SELECTED inside of the option like <option value="the Topic ID" SELECTED> when the $FK_TopicID is equal to $row['TopicID'].
I am just not sure how to check the $FK_TopicID within the while loop for $topresult. Any ideas?
<?php
$NewsID = $_GET["n"];
$quickedit = mysql_query("SELECT * FROM News LEFT JOIN Topics on Topics.TopicID = News.FK_TopicID WHERE NewsID = $NewsID ORDER BY TopicName ASC, NewsTitle");
$row = mysql_fetch_array($quickedit);
echo "<p>" . $FK_TopicID . "</p>";
/* additional php... */
$topresult = mysql_query("SELECT * FROM Topics WHERE FK_UserID=$_SESSION[user_id] ORDER BY TopicSort, TopicName");
while($row = mysql_fetch_array($topresult)) {
if ( $row['TopicID'] == $FK_TopicID){ /* $FK_TopicID not printing value here */
$selected = " SELECTED";
} else {
$selected = "";
}
echo '<option value=\"' . $row['TopicID'] . '" ' . $selected . '>' . $row['TopicName'] . '</option>';
}
?>
I have no clue about the structures of the database, but I'll give it a shot
Does this output something you want?
<?php
$NewsID = $_GET['n'];
$quickedit = mysql_query("SELECT * FROM News LEFT JOIN Topics on Topics.TopicID = News.FK_TopicID WHERE NewsID = $NewsID ORDER BY TopicName ASC, NewsTitle");
$topresult = mysql_query("SELECT * FROM Topics WHERE FK_UserID=$_SESSION[user_id] ORDER BY TopicSort, TopicName");
echo "<p>" . $FK_TopicID . "</p>";
while($row = mysql_fetch_array($quickedit)) {
while($row2 = mysql_fetch_array($topresult)) {
if ( $row2['TopicID'] == $row['FK_TopicID']){
$selected = " SELECTED";
} else {
$selected = "";
}
echo '<option value=\"' . $row2['TopicID'] . '" ' . $selected . '>' . $row['TopicName'] . '</option>';
}
}
?>
This code loops through both queries and if the TopicID from $topresult is equal to the FK_TopicID from $quickedit, it will be selected.