I'm trying to get an HTML SELECT field within a form to be populated from a database column. I can read the column fine, and can use fprint or echo to see the results. The problem is, I can't seem to get the array based on the column to appear as selections in the SELECT field. I'm able to produce a field with a pull-down selector, but the values aren't populated. How to I get the values from the Array into an HTML SELECT / OPTION field?
Here's a subset of the code I'm using:
<?php
$link = new mysqli("localhost","USER","PASSWORD", "DATABASE");
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!$link->set_charset("utf8"))
{
printf("Error loading character set utf8: %s\n", $link->error);
exit();
}
$role_sql = "SELECT role FROM lu_role";
$role_result = mysqli_query($link, $role_sql);
$options = "";
while($row1 = mysqli_fetch_array($role_result))
{
$options = $options."<option>$row1[1]</option>";
}
//Using the following to validate that I can get the query results in an array.
while ($row = $role_result->fetch_assoc())
{
printf($row["role"]);
}
?>
<form action="post.php" method="post">
<table class="table_600_reg">
<tr>
<td width="120">Father</td>
<td width="200" align="left">
<select>
<?php echo $options;?>
</select>
You may check your index in displaying your field. On your query, you only specified a field to be returned:
SELECT role FROM lu_role
So the index should start with '0' not '1'.
$options = $options."<option>$row1[0]</option>";
You may also use 'mysqli_fetch_assoc' so you can use $row1['role'] instead of relying on the index.
You are missing value="" here $options = $options."<option value='VALUE_HERE'>$row1[1]</option>";
And since you are selecting only one column it should be $row1[0] instead of $row1[1]
Try this :
$options = "";
while($row1 = mysqli_fetch_array($role_result))
{
$options .= "<option value='".$row1['role']."'>$row1['role']</option>";
}
and then can you able to use
<select>
<option value="">Select one</option>
<?php echo $options;?>
</select>
I would personally refer to the associative array values instead of the indexed values. If you later decided you wanted to pull more results from that table to manipulate other data, the index could change.
while ($row = $role_result->fetch_assoc()) {
$options .= "<option value='{$row['role']}'>{$row['role']}</option>";
}
you need to put your while statement inside the select tag
here is the code
<select>
<?php
while($row1 = mysqli_fetch_array($role_result))
{
$options = $options."<option>$row1[1]</option>";
echo '$options';
}
?>
</select>
Related
Right now I am having trouble with splitting up entries in my ethnicity column that contain entries that are separated by commas for example take a look at my
Ethnicity table
I want to be able to split up these strings into individual strings so they can all be their own entries (ex: asian, chinese, catina would all be seperate entries). I don't want to make any changes to my existing table I just want to be able to seperate these strings because I am using php to create a dynamic drop down list based on what is stored in this ethnicity column:
<h3>*Category</h3>
<select name="category" multiple>
<?php
$conn = mysqli_connect(db, root, pass, table);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$result = mysqli_query($conn,"SELECT DISTINCT restaurant_id, ethnicity FROM ethnicity");
while ($row = mysqli_fetch_assoc($result)) {
unset($restaurantID, $ethnicity);
$restaurantID = $row['restaurant_id'];
$ethnicity = $row['ethnicity'];
echo '<option value="'.$ethnicity.'">'.$ethnicity.'</option>';
}
?>
</select>
Right now the drop down list is including the comma separated strings and I just want it to be able to display the distinct ethnicities individually. Any suggestions?
I'd start buy doing the query above and exploding all the ethnicities into a new array and then printing them out:
(I haven't tested syntax just used notepad, hopefully you get the idea though.)
<h3>*Category</h3>
<?php
$conn = mysqli_connect(db,root,pass,table);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$ethnicity_array = [];
$result = mysqli_query($conn,"SELECT DISTINCT restaurant_id, ethnicity FROM ethnicity");
while ($row = mysqli_fetch_assoc($result))
{
unset($restaurantID, $ethnicity);
$restaurantID = $row['restaurant_id'];
$ethnicity = $row['ethnicity'];
$split_ethnicity = explode("," $ethnicity);
foreach ($split_ethnicity as $value)
{
if (!in_array($value, $ethnicity_array))
$ethnicity_array[] = $value;
}
}
?>
<select name="category" multiple>
<?php
foreach ($ethnicity_array as $ethnicity)
{
echo '<option value="'.$ethnicity.'">'.$ethnicity.'</option>';
}
?>
</select>
I want to show options from my database for users to check, but having trouble getting user's choice.
So, I write two php files,
the first one doing things like: getting data from database, displaying in select option, then submit value by post to and the second php file.
And the second php file just display the recieved value.
Here's the first php file:
<html>
<body>
<form method="post" action="second.php">
<Select name=”select_value”>
<?
//connect to server
$con = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE) or die("Error " . mysqli_error($con));
$query = "SELECT * FROM MYTABLE" or die("Error in the consult.." . mysqli_error($con));
$result = $con->query($query);
//display result in select option
while ($row = mysqli_fetch_array($result)) {
echo "<Option value=".$row['ENTRY_ID']."> ".$row['ENTRY_NAME']."</Option><br>";
}
mysqli_close($con);
?>
</Select>
</form>
</body>
</html>
And the second php file:
<?
$option = isset($_POST['select_value']) ? $_POST['select_value'] : false;
if($option) {
echo $_POST['select_value'];
} else {
echo "not getting value of select option";
exit;
}
?>
If this works fine, I should see the selected value by the second php file, but I keep recieving my echo "not getting value of select option".
There must be something wrong between select option and my recieving file.
Can someone help?
try this double quotes
<Select name="select_value">
instead of <Select name=”select_value”>
Echo 'Hello programmers' ;
I'm scratching my head about a pair of drop down menus. They are supposed to display all strings from the ename and mid rows. However this isn't happening and the drop down is only displaying one result from each row. There are multiple strings of test data in the actual rows.
I have some code here and perhaps you could lend a hand. Let me explain.
First off these are the methods from class dbme. To keep the clutter down the second function is exactly the same, except the SQL query for getResult() is obviously different (SELECT * from member as opposed to memberevent)
function openDB() {//creating database connection
$conn = mysqli_connect("localhost", "root", "", "mydb");
if (!$conn) {
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
function getResult($sql){
$result = mysqli_query($this->conn , "SELECT * from memberevent" );
if ($result) {
return $result;
} else {
die("SQL Retrieve Error: " . mysqli_error($this->conn));
}
}
Second, this is the web-side data.
$db1 = new dbme();
$db1->openDB();
$sql="select mid from member";
$result=$db1->getResult($sql);// get the ids from the tables for the select
$sql1="select ename from event";
$result1=$db1->getResult($sql1);// get the ids from the tables for the select
if (!$_POST) //page loads for the first time
{
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" onsubmit="return validateForm( );">
Select Member ID: <select name="mid">
<?php
while($row = mysqli_fetch_assoc($result))
echo "<option value='{$row['mid']}'>{$row['mid']} </option>";
?>
</select>
<br />
Select Event name : <select name="ename">
<?php
while($row = mysqli_fetch_assoc($result1))
echo "<option value='{$row['ename']}'>{$row['ename']} </option>";
?>
</select>
<br />
I have a sneaking suspicion that a variable is getting over written, OR an extra loop is needed somewhere. But I'm not really sure, thus I post this question for advice.
Thanks.
You need to iterate through your results inside your getResults() function, otherwise you will always only get one row.
You are passing in the SQL but never using it:
Change
function getResult($sql){
$result = mysqli_query($this->conn , "SELECT * from memberevent" );
To
function getResult($sql){
$result = mysqli_query($this->conn , $sql );
Okay so I have a table called Countries and it looks like this:
---------------------------
|Country | Code |
---------------------------
|Afganastan | AF |
|ÅLAND ISLANDS| AX |
| etc. | etc. |
---------------------------
The thing that I want to do is create a dynamic menu in which the user chooses a country and that itself gets stored as a value that I can call after the user hits submit.
I did try something here but I'm not sure what its doing because I am still new to PHP and HTML to the point where I just type things in to see what would happen.
Anyways I am really stuck and I tried using google and the search feature in this site and nothing I found worked for me...
The code I tried is this:
<select>
<?php
$result = mysql_query('SELECT Country FROM Countries');
echo '<select name="country">';
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
echo '</select>';
?>
</select>
The result is supposed to look like a dropdown menu with the list of countries from the database in it. But this doesn't work and just shows this in the drop down:
.$row['name']
Which is nothing close to what I want because that's not even a country. when I remove that part of the code, then there is no option for the user to choose, the menu is empty.
EDIT
My code so far that still doesn't work:
<select name = 'country'>
<?php
include ("account.php");
include ("connect.php");
$result = mysql_query('SELECT Code , Country FROM Countries');
while ($row = mysql_fetch_array($result))
{?>
<option value="<?php echo $row['Code']?>"><?php echo $row['Country']?></option>
<?php}
?>
</select>
The include ("account.php"); and include ("connect.php"); lines allow me to connect to my database.
you code should be something like this
$host = "localhost";
$user = "root";
$pass = "yourpassword";
$db = "databasename";
// This part sets up the connection to the
// database (so you don't need to reopen the connection
// again on the same page).
$ms = #mysql_connect($host, $user, $pass);
if ( !$ms )
{
echo "Error connecting to database.\n";
}
// Then you need to make sure the database you want
// is selected.
#mysql_select_db($db);
<form method = "POST" action = "abc.php">
<select name = 'country'>
<?php
$result = mysql_query('SELECT id , name FROM Countries');
while ($row = mysql_fetch_array($result))
{?>
<option value="<?php echo $row['id']?>"><?php echo $row['name']?></option>
<?php}
?>
<input type = "submit" value = "Submit">
</form>
Now in php use this
echo '<pre>';
print_r($_POST);
And you will see what user selected. Check your settings there might be some problem.
Your single and double quotes are messing you up:
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
should be:
echo "<option value=\"" . $row['id'] . "\">" . $row['name'] . "</option>";
You can use a single quote around your script but when you jump out of it to do the $row['id'] and $row['name'] you are running into issues because it thinks you are jumping back into your quoted code... Either use my example above, starting/ending with double-quotes and escaping all double-quotes inside that need to display, or escape your single quotes in the $row[\'id\'] and $row[\'name\']
Thant should help you out.
Try this code
<?php
$result = mysql_query('SELECT * FROM Countries');
?>
<select name="country">
<?php
while ($row = mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
<?php
}
?>
</select>
Firstly your table doesn't have a column id. Try changing your query like
SELECT Country, Code FROM Countries
Then the code and the html should be like this
<?php
$host = "localhost";
$user = "user"; //username
$pass = "pass"; //password
$db = "db"; //database
$con = #mysql_connect($host, $user, $pass);
if ( !$con )
{
echo "Error connecting to database.\n";
}
#mysql_select_db($db);
?>
<select name="country">
<option value="0" selected="selected">Choose..</option>
<?php
//echo '<select name = \'country\'>';
$result = mysql_query('SELECT Country, Code FROM Countries');
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['Code'].'">'.$row['Country'].'</option>';
}
?>
</select>
<select>
<?php
$result = mysql_query('SELECT Country FROM Countries');
echo '<select name="country">';
$row = mysql_fetch_array($result)
for ($i=0; $i<count($row ); $i++)
{
echo '<option value="'.$row[$i]['id'].'">'.$row[$i]['name'].'</option>';
}
echo '</select>';
?>
next page use print_r($_POST);
or var_dump($_REQUEST);
If you are using mysql_fetch_array you can use either the field names or their selected index to read them from the fetched row. You can also use either the sprintf or printf functions to merge content into a string to help keep the HTML fragment clean of the quotes needed to merge in values otherwise.
$result = mysql_query('SELECT Country, Code FROM Countries');
while ($row = mysql_fetch_array($result)) {
printf('<option value="%1$s">%2$s</option>',
$row['Code'], $row['Country']);
}
Your SQL statement selected only 'Country' from the 'Countries' table; as a result, it's impossible for you to use $row['id'] and $row['name'].
Use this instead:
echo '<select name="country">';
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['Code'].'">'.$row['Country'].'</option>';
}
echo '</select>';
?>
That should solve your problem.
I figured out the problem I was having. The first being that there was an extra select tag in the page and the second that the file was saved as a html page instead of a php file. Thank you to everyone that helped me figure this out!
Try my code, I'm using this and it really works... just change the values...
<?php
include ('connect.php');
$sql = "SELECT * FROM casestatusfile";
$result = mysql_query($sql);
echo "<select name = 'txtCaseStatus'/>";
echo "<option value = ''>--- Select ---</option>";
$casestatus = $_POST['txtCaseStatus'];
$selected = 'selected = "selected" ';
while ($row = mysql_fetch_array($result)) {
echo "<option " .($row['CASESTATUSCODE'] == $casestatus? $selected:''). "value='". $row['CASESTATUSCODE'] ."'>" . $row['CASESTATUS'] ."</option>";
}
echo "</select>";
?>
I'm sure that is working because that is the one that i'm using....
So, im creating a form that will submit data into an SQL database. Ive got 2 select drop downs that hold the data of "Module Code" and "Module Title". In the database a module title will only have one module code e.g Team project(module title) has module code 11COB290.
How can i get it so that when a user selects a given module name OR Module title is will automatically select the correct partner i.e select the right module code thats related to the module name the user has selected without pressing any submit buttons?
The following code is the drop down select boxes and php code i have so far:
<td align="center">
<select name='ModuleTitle' id='ModuleTitle' style='width:100%;'>
<option>Select...</option>
<?php
//3. Perform database query
$result = mysql_query("SELECT * FROM Module
ORDER BY `ModTitle` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row = mysql_fetch_array($result)) {
$module = $row[2];
echo "<option name='{$module}'>{$module}</option><br />";
}
?>
</select>
</td>
<td align="center">
<select name='ModuleCode' id='ModuleCode' style='width:100%;'>
<option>Select...</option>
<?php
//3. Perform database query
$result = mysql_query("SELECT * FROM Module
ORDER BY `ModCode` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row = mysql_fetch_array($result)) {
$module = $row[3];
echo "<option name='{$module}'>{$module}</option><br />";
}
?>
</select>
</td>
Unless there is a special reason to do so, why not give a single SELECT box instead of two?
<td align="center">
<select name='ModuleTitle' id='ModuleTitle' style='width:100%;'>
<option>Select...</option>
<?php
//3. Perform database query
$result = mysql_query("SELECT * FROM Module ORDER BY `ModTitle` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row = mysql_fetch_array($result)) {
$module = $row[2] . ' (' . $row[3] . ')';
$moduleCode = $row[3];
echo "<option value='{$moduleCode}'>{$module}</option>";
}
?>
</select>
</td>
Or otherwise if you would like to keep 2 SELECTs, use AJAX calls. The idea is to define onChange event on each SELECT and in that event, send an AJAX request to a PHP script. The PHP script will request the module code or title and send it back to the AJAX handler. The AJAX handler can then automatically mark as SELECTED the corresponding option in the other SELECT. You might need sometime to research on AJAX and JavaScript if you aren't already experienced with this stuff.
Another idea might be to use the module code as the value for the title SELECT and module title as the value for the code SELECT. For example, title SELECT will be:
<SELECT name="ModuleTitle" id="ModuleTitle" style="width:100%;">
<OPTION>Select...</option>
<OPTION value="123">Title 123</OPTION>
<OPTION value="345">Title 345</OPTION>
<OPTION value="567">Title 567</OPTION>
</SELECT>
Then in the onChange event handler you might do something like this:
var selObj = document.getElementById('ModuleTitle');
var selIndex = selObj.selectedIndex;
document.getElementById('ModuleCode').value = selObj.option[selIndex].text;
By the way, there is no "name" attribute for . It should be "value" instead. Please fix in your code.
Hope it helps!
CAUTION: none of the above code is tested but I hope it works fine