Populating drop-down list with PHP not working - php

I am trying to get a drop-down list populated with PHP to my website but it is not displaying anything. It's empty as shown in this image. Under the state it shows nothing.
Please help me to get some details from my database results.
My code is:
<?php
$con=mysql_connect('localhost', '', '')or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db('')or die("Failed to connect to MySQL: " . mysql_error());
?>
<form>
<div class="form-group">
<div class="form-control-small">
<select id="search_status" name="state" data-placeholder="State">
<option value=""> </option>
<?php
$dd_res=mysql_query("Select DISTINCT state from MyTable");
while($row=mysql_fetch_row($dd_res))
{
echo "<option value='$row[state]'> $row[state] </option>";
}
?>
</select>
</div>
<div class="form-control-small">
<select id="search_bedrooms" name="dist" data-placeholder="District">
<option value=""> </option>
<?php
$dd_res=mysql_query("Select DISTINCT dist from MyTable");
while($r=mysql_fetch_row($dd_res))
{
echo "<option value='$row[dist]'> $row[dist] </option>";
}
?>
</select>
</div>
<div>
<button type="submit" class="btn btn-fullcolor">Search</button>
</div>
</div>
</form>

Try some thing like this:
$arr = array(1 => 'MP', 2 => 'UP');
echo '<select>';
foreach($arr as $key => $val)
{
echo '<option value="'.$key.'">'.$val.'</option>';
}
echo '</select>';
It will generate html like:
<select>
<option value="1">MP</option>
<option value="2">UP</option>
</select>

You cant display Array values in a string, even with double quotes.
Either you have to use curly brackets or concatenation
echo "<option value='{$row[state]}'> {$row[state]} </option>";
or
echo "<option value='".$row[state]."'> ".$row[state]." </option>";

Try this:
echo "<option value='".$row['state']."'> ".$row['state']."</option>";

According to the documentation, the mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
This means that you cannot reach your column names like this: $row["state"].
Try instead:
echo "<option value='$row[0]'> $row[0] </option>";
However the mysql_query and mysql_fetch_row function are deprecated, and they will be removed in PHP version 7. It can be an issue for you too. Consider upgrading to something more modern way of interacting with MySQL.
You will find alternatives here:
http://php.net/manual/en/mysqlinfo.api.choosing.php

Related

Dynamic Dropdown List PHP MYSQL

I am new to PHP and trying to make dynamic list box using SQL
<label> Select Sport</label>
<select name = "Sport">
<option value = "">Select Sport</option>
<?php
$all = "SELECT * FROM EventTable";
$result = $pdo->query($all);
foreach($result as $Sport){
?>
<option value ="<?php echo $Sport['Sport']; ?>"></option>
<?php
}
?>
</select>
But its printing BLANK space
Try this:
<select name="">
foreach($result as $Sport){
?>
<option value ="<?php echo $Sport['Sport']; ?>"><?php echo $Sport['Sport']; ?></option> // The value between <option> value </option> is the value which is to be shown in the dropdown, without this it is showing blank
<?php
}
</select>
You probably shouldn't use SELECT *, but since you're learning, I digress. Also, I personally have a hard time reading a lot of opening and closing php tags scattered throughout plus they often give weird results than what you're expecting, so this is how I'd write it.
<?php
$all = "SELECT * FROM EventTable";
$result = $pdo->query($all);
foreach($result as $sport)
{
echo "<option value =" . $sport['Sport'] . ">" . $sport['Sport'] . "</option>";
}
?>
The blank spaces indicates that you are actually hitting the loop and iterating, but the values for that array item are null. Are you sure the field name isn't 'sport' instead of 'Sport'?

PHP populate using data from table

I'm trying to populate drop down option with the data from table :
<?
$sqloption="SELECT name FROM user";
$resultoption=mysql_query($sqloption);
$options="";
while ($row=mysql_fetch_array($resultoption))
{
$nameoption[]=$row['name'];
$options.="<OPTION>".$nameoption</option>";
}
?>
<SELECT>
<OPTION>Choose user<?=$options?>
</SELECT>
The button is getting displayed but it has no options. How do I correct this?
Why are you storing them in an another array? Fix the errors. Just do -
PHP
while ($row=mysql_fetch_array($resultoption))
{
$options.= "<OPTION>". $row['name'] ."</OPTION>";
}
HTML
<SELECT>
<OPTION>Choose user</OPTION>
<?=$options?>
</SELECT>
You can populate the dropdown menu using many method:
mysql_fetch_array() fetches a result row as an associative array, a numeric array, or both. It returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how $result_type is defined.
<?php
$sql="SELECT name FROM user";
$result=mysql_query($sql);
?>
<select name="user">
<?php while ($row=mysql_fetch_array($result)){ ?>
<option value="some_value"><?php echo $row['name'];?></option>
<?php } ?>
<select>
mysql_fetch_assoc() fetches a result row as an associative array. (column names as key)
<?php while ($row=mysql_fetch_assoc($result)){ ?>
<option value="some_value"><?php echo $row['name'];?></option>
<?php } ?>
mysql_fetch_object() fetches the result row as an object.
<?php while ($row=mysql_fetch_object($result)){ ?>
<option value="some_value"><?php echo $row->name;?></option>
<?php } ?>
<?
$sqloption="SELECT name FROM user";
$resultoption=mysql_query($sqloption);
$options="";
while ($row=mysqli_fetch_array($resultoption)) {
$nameoption[]=$row['name'];
$options.="<OPTION>".$row['name']."</option>";
}
?>
<SELECT>
<OPTION>Choose user<?=$options?>
</SELECT>
You've forgotten a "." after $nameoption.
And by the way, you cannot do $options.="<OPTION>".$nameoption</option>";
because it's an array. PHP can't print an array() directly.
I've kept your $nameoption if you need it. Also, I suggest switching from mysql to mysqli because mysql_ is deprecated.

How can I arrange my form with html and php

The problem I have is that there is no results in the "category" option. I tried to use two whiles but that doesn't work either.
This is my php:
try{
$sel=$pdo->prepare("Select * from
actors inner join cat
on actors.id=cat.id");
$sel->bindColumn(1,$actors_id);
$sel->bindColumn(2,$actors);
$sel->bindColumn(3,$cat_id);
$sel->bindColumn(4,$cat);
$sel->execute();
}catch(PDOException $e){
die("error: " . $e->getMessage());
}
And This is my html:
<form action="" method="post">
<label for="author">Author</label>
<Select id="author">
//Show data from php file:
<?php while($sel->fetch()):?>
<?php echo "<option value='$actors_id'>$actors</option>";?>
<?php endwhile; ?>
</Select>
<label for="category">Category</label>
<Select id="category">
//Show data again from php file:
<?php while($sel->fetch()):?>
<?php echo "<option value='$cat_id'>$cat</option>";?>
<?php endwhile; ?>
</Select>
</form>
And this is how it looks like:
As you can see, there is no info display in the "category" option.
If I change the html to something like this, it doesn't work either:
<Select id="author">
<?php while($sel->fetch()):?>
<?php echo "<option value='$actors_id'>$actors</option>";?>
</Select>
<label for="category">Category</label>
<Select id="category">
<?php echo "<option value='$cat_id'>$cat</option>";?>
<?php endwhile; ?>
</Select>
Now it looks like this:
Do you have any suggestion?
Your first while loop fetches all rows from the PDOStatement object, so when you call while ($sel->fetch()) a second time, it immediately returns false. If you want to use the results in essentially two separate loops, fetch all rows first into an array of rows, then loop over that array. Do so with fetchAll() instead of binding to variables via bindColumn().
In fact, I would almost always recommend fetching first rather than during the display logic, except for very large rowsets where the memory consumed by fetching it all at once would be taxing on your system.
// Get all the rows as an array
$rows = $sel->fetchAll(PDO::FETCH_ASOC);
// Later loop for the items you need as many times as you need
// Each new foreach will iterate the entire $rows array from start to end
<?php foreach ($rows as $row): ?>
<?php echo "<option value='{$row['actors_id']}'>" . htmlspecialchars($row['actors']) . "</option>";?>
<?php endforeach; ?>
<?php foreach ($rows as $row): ?>
<?php echo "<option value='{$row['cat_id']}'>" . htmlspecialchars($row['cat']) . "</option>";?>
<?php endforeach; ?>
Don't forget to call htmlspecialchars() on the output, to ensure it is properly encoded for HTML. I haven't done so on cat_id,actors_id on the assumption those are known to be integers, but if not, then you should use htmlspecialchars($row['cat_id'], ENT_QUOTES) to ensure the HTML attributes are correctly quoted.
You need to be cleaner in your return -
<?php
$result = $sel->fetchAll(PDO::FETCH_OBJ); //return an object
foreach($result as $actor) {
echo '<option value=' . $actors->actor_id .'>'. $actor->actors .'</option>'; // note the quotes
}
?>
You can loop through the result as many times as you need to, without re-fetching the data.

how do i get the $_POST to pass the variable to the next page

I have been working on this for days and can get it working. I have a website that allows players to select their team from a SQL database. I populate the drop down list using the following code. This passes the same values to all six drop down lists.
while($row = mysql_fetch_array($result))
{
$strName = $row['FirstName']." ".$row['LastName'];
$options.= "<OPTION Value=name>".$strName;
}
mysql_close($conn);
?>
<div id="input_options">
<form name="form1" method="post" action="savegolfervalues.php">
<span > Golfer 1 </span>
<select name="golfer1" size="1" style="font-size:15px;">
<option value="0">Golfer 1 </option>
<?=$options?>
</select>
</br>
...
This happens for 5 different drop down lists. Ech named differently, golfer2-golfer5
<input type="submit" name="Submit" value="Set Lineup">
</form>
The savegolfervalues.php page just does the echo:
<h1>Golfer 1 is :
<?php
$g1 = $_POST['golfer1'];
echo ($g1);
?>
</h1>
etc.
However--nothing gets passed across--the echo doesn't bring the names across.
What am I missing?
Be aware that value of option is passed under $_POST['golfer1']; and not name or label itself... so it should be 0 in your case.
<option value="0">Golfer 1 </option>
is not
<option value="Golfer 1">Golfer 1 </option>
$options.= "<OPTION Value=name>".$strName;
close option tag:
$options.= "<OPTION value='".$strName."'>".$strName."</OPTION>";
Add quotes to the attribute value and the variable $strName

Displaying a php mysql result with two values with a foreach loop in PHP

I have result that I want to display as a drop down menu. The query selects id and name from a table.
$usersQuery = "SELECT id, name
FROM users";
$usersResult = mysqli_query ($dbc, $usersQuery);
I want to use this result as a list in a drop down menu. This is what i have so far.
<select id="dropdown" name="dropdown">
<option value="select" selected="selected">Select</option>
<?php
while ($usersRow = mysqli_fetch_array($usersResult, MYSQLI_ASSOC)){
foreach ($usersRow as $value){
echo "<option value=\"$value\"";
echo ">$value</option>\n";
}
}
?>
</select>
this would work fine if I just wanted to display name as both the value and the display to the user. But what I want to do is use the selected id as "value" for the select option and I want to show the name selected to the user. I have tried this but it does not work.
<select id="dropdown" name="dropdown">
<option value="select" selected="selected">Select</option>
<?php
while ($usersRow = mysqli_fetch_array($usersResult, MYSQLI_ASSOC)){
foreach ($usersRow as $id=>$name){
echo "<option value=\"$id\"";
echo ">$name</option>\n";
}
}
?>
</select>
Any help would be great.
Thanks in advance.
mysqli_fetch_array() is a function which converts your query results into an array. which means you can display your values like you would with a normal array value.
<select id="dropdown" name="dropdown">
<option value="select" selected="selected">Select</option>
<?php
while ($usersRow = mysqli_fetch_array($usersResult, MYSQLI_ASSOC)){
echo "<option value=\"".$usersRow['id']."\"";
echo ">".$usersRow['name']."</option>\n";
}
?>
</select>
No need for the foreach iteration; mysqli_fetch_array() already provides an associative array. After each fetch do
// Assuming "id" is a numeric value
printf('<option value="%d">%s</option>', $usersRow['id'], $usersRow['name']);
The foreach is unnecessary - using a while loop on the mysqli_fetch_array command will return all the results with each row in an array - you can use it like so:
while ($usersRow = mysqli_fetch_array($usersResult, MYSQLI_ASSOC)){
echo "<option value=\"".$usersRow['id']."\"";
echo ">".$usersRow['name']."</option>\n";
}

Categories