I am populating a select option using a php while loop from a mysql table. The following is the php code:
<?php
session_start();
$database = $_POST['folder'];
include('connect.php');
$connect = mysqli_connect($hostname, $username, $password,$database );
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
$result = $connect->query("select name from treeview where parent_id = 1;");
?>
<option value="">Select Location</option>
<?php while($row1 = mysqli_fetch_array($result)):;?>
<option value="<?php echo $row1['name'];?>"><?php echo $row1['name'];?></option>
<?php endwhile;?>
This works correctly, except for the fact that the fetched items are not sorted alphabetically. I understand this could be trivial, but I couldn't get it right. I tried the following:
Option 1
<?php while($row1 = mysqli_fetch_array($result)):;
$row1 = sort($row1);
?>
<option value="<?php echo $row1['name'];?>"><?php echo $row1['name'];?></option>
Option 2:
<?php while($row1 = mysqli_fetch_array($result)):;?>
<option value="<?php echo sort($row1['name']);?>"><?php echo sort($row1['name']);?></option>
Both didn't work.
You need to change your SQL query and use ORDER BY
See here link
You are attempting to sort a single row, instead of between the rows. Sorting all the rows will require you to fetch them all of them and then sort them. An easier approach, IMHO, would be to sort them in the query itself:
$result = $connect->query("select name from treeview where parent_id = 1 ORDER BY 1;");
# Here ------------------------------------------------------------------^
Related
The function of this web application is to: select a customer from the dropdown list (the dropdown list values are auto popup from the database), it will print the selected customer name and its postcode on the result page.
When I choose the customer name from the dropdown list and click the submit button, the result page only prints the $customerv value (the 1st echo), but the $result value (2nd echo) was not printed. The customer name is unique in the database.
index.php:
<?php
require_once('config.php');
?>
<!DOCTYPE HTML>
<html>
<form action="result.php" method="post">
Customer:<br>
<select Customer id="customer" name="Customer">
<option value="">--- Select Customer ---</option>
<?php
$sql = "SELECT b.BPName from BP b where b.BPCode like 'C%' Order by b.BPName";
$customer = mysqli_query($conn, $sql);
while ($cat = mysqli_fetch_array(
$customer,
MYSQLI_ASSOC
)) :;
?>
<option value="<?php echo $cat['BPName']; ?>">
<?php echo $cat['BPName']; ?>
</option>
<?php
endwhile;
?>
</select>
<input type="submit" value="Submit">
</form>
</html>
config.php:
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$databse = "xxx";
$conn = new mysqli($servername, $username, $password, $databse);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
result.php:
<table>
<?php
require_once('config.php');
$customerv = $_POST['Customer'];
echo $customerv;
$sql = "SELECT shiptozipcode FROM BP WHERE BPName ='$customerv'";
$result = $conn->query($sql);
echo $result;
?>
</table>
The query result itself isn't something that's "printable" to the page. It's not just a single value, it's a complex object. You need to fetch the record(s) from the result. For example:
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo $row["shiptozipcode"];
}
If you're sure there will be only one row (it's still a good idea to add some error checking anyway) then you don't need the loop:
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $row["shiptozipcode"];
But either way, you need to extract the data from the result set. (You could also use fetch_object() instead of fetch_assoc() if you prefer object syntax over array syntax.)
As an aside, be aware that your query is wide open to SQL injection. Now would be a good time to learn how to correct that.
I want to do the next thing but I don't know how to do this, I'll try to explain me
I have an field generated by php code like this (Works)
<select id="profiles_select" name="profiles_select">
<?php
do {
?>
<option value="<?php echo strtoupper($system['profile']);?>">
<?php echo strtoupper($system['profile']);?></option>
<?php
} while($system = mysql_fetch_assoc($r)); //the "$r" it's the query
$rows = mysql_num_rows($r);
if($rows > 0) {
mysql_data_seek($r, 0);
$systemas = mysql_fetch_assoc($r);
}
?>
</select>
The query
<?php
$q="SELECT DISTINCT profile FROM sys_profiles";
$r=mysql_query($q,$ConecLocal) or die(mysql_error());;
$systemas=mysql_fetch_assoc($r);
$tsys=mysql_num_rows($r);
?>
What I need?
I need generate another similar to first generated by php code but, this time I need made a Query including the value of the first , something like this:
<?php
$value_select=$_GET['profiles_select'];
$q2="SELECT DISTINCT systems FROM sys_profiles where profile=$value_select";
$r2=mysql_query($q,$ConecLocal) or die(mysql_error());;
$profiles2=mysql_fetch_assoc($r);
$tsys=mysql_num_rows($r);
?>
Next of the query I need show in the another the query result, something similar to the first select (generated by php), but do the query when the first of the it's selected
<select id="systems_select" name="system_select">
<?php
do {
?>
<option value="<?php echo strtoupper($system['systems']);?>">
<?php echo strtoupper($profiles2['systems']);?></option>
<?php
} while($profiles2 = mysql_fetch_assoc($r2)); //the "$r2" it's the another query
$rows2 = mysql_num_rows($r2);
if($rows2 > 0) {
mysql_data_seek($r2, 0);
$systemas = mysql_fetch_assoc($r2);
}
?>
</select>
Thanks for the help.
SO I have about 60 fields of data queried from a database. They look like this in page source:
<option>Genesis</option>
<option>Exodus</option>
<option>Leviticus</option>
For example I wanna have it so that 1-20 are a certain optgroup and then 20-60 is another. Could I do it using my format of options of would they have to be numbered like this:
<option value="1">Genesis</option>
<option value="2">Exodus</option>
<option value="3">Leviticus</option>
This is for my php class, but i dont think php is involved in making optgroups here, or is it? Thank you hope you understand my question. Hoping for help.
I pull the data from mysql using this :
//Query the database for the results we want
$query = $mysqli->query("select distinct bname as Name from kjv"); ?>
And then output it in the select dropdown box using this:
<select>
<?php while($option = $query->fetch_object()){ ?>
<option><?php echo $option->Name; ?></option>
<?php } ?>
</select>
Use:
<select>
<?php
$i=1;
while($option = $query->fetch_object()){
if($i%10==1) echo "<optgroup label='Option Group'>";
echo "<option value='$i'>".$option->Name."</option>";
$i++;
if($i%10==1) echo "</optgroup>";
}
?>
</select>
Using while loop :
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
foreach ($row = mysql_fetch_array($result)) {
echo "'<option value={$row['id']}>{$row['value']}</option>'";
}
i try to get data from mysql db into html dropdown , i execute the query in PHPmyadmin and its work fine , the result is one record,and all the website is connected with theses details of MYSQL my code is :
<?php
mysql_connect("localhost", "root", "1212") or die("Connection Failed");
mysql_select_db("test")or die("Connection Failed");
$query = "SELECT department_name FROM department";
$result = mysql_query($query);
?>
<label for="department" > Department Name </label>
<select name="departments" >
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['field'];?>"> <?php echo $line['field'];?> </option>
<?php
}
?>
</select>
the output is drop-down with one empty record , any one can help me in that ?
First required statement: mysql_ is deprecated. mysqli_ should be used instead.
Second ...
Did you try $line['department_name'] instead of $line['field'] ?
Well first of all you should print the results of the query to ensure the array structure is what you think it is.
This would have shown you that there is no column in the result set named field as you seem to believe due to this line of code:
<option value="<?php echo $line['field'];?>"> <?php echo $line['field'];?> </option>
As to why you only get one option, my first bit of advice will probably shed some light on said issue as well.
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....