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.
Related
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
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'?
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.
I have the below code. It's a function creating a from containing a dropdown menu and a selectionbox, and is being called from a different page).
<?php
require_once 'forbindtilDB.php';
function populerDropdownsOpretProgram()
{
global $mysqliOOP;
$stmt = $mysqliOOP->prepare("SELECT DISTINCT primaer FROM oevelser ORDER BY primaer ASC");
?>
<form action="temp.php" method="post">
<select multiple>
<option value="0">Vælg ønskede øvelse(r)</option>
<?php
$stmt->execute();
$stmt->bind_result($primaereMuskelgruppe);
while ($stmt->fetch())
{
?>
<option value = "<?php echo $primaereMuskelgruppe;?>" >
<?php echo $primaereMuskelgruppe;
?>
</option>
<?php
}
$stmt->close();
?>
</select>
<?php
$stmt = $mysqliOOP->prepare("SELECT antalreps FROM antalreps ORDER BY antalreps ASC");
?>
<select>
<option value="0">Vælg ønskede antal gentagelser</option>
<?php
$stmt->execute();
$stmt->bind_result($antalreps);
while ($stmt->fetch())
{
?>
<option value = "<?php echo $antalreps;?>" >
<?php echo $antalreps;
?>
</option>
<?php
}
$stmt->close();
?>
</select>
<input type="submit">
</form>
<?php
}
I want to post the user input on a different page (currently temp.php), but I don't know how to handle the fact that the form contents is variables fetched by a mysqli call.
So far I've tried different versions of the below on the temp.php-page
<?php
echo $_POST[$antalreps];
?>
<?php
echo $_POST[$primaereMuskelgruppe];
?>
But I'm getting errors stating that there is undefined variables (antalreps and primaeremuskelgruppe) and undefined indexes...
Also, there's the added complexity that the selection box may return more than one result.
Pretty sure echo $_POST[$antalreps]; etc. is the wrong way to go about this, but I haven't been able to figure out alternatives...
Any hints?
You should add 'name' to your select and then use it.
For example instead of:
<select>
you should have:
<select name="yourname">
and then in php to display its value use:
echo $_POST['yourname'];
and for select multiple you can use:
<select name="othername[]">
and then in PHP use it as array:
foreach ($_POST['othername'] as $item) {
echo $item;
}
of course where I put yourname and othername you should put descriptive name such as colours for color box and similar
I have a drop down menu that I want to change to a multiple select box. The code below is working if you only select 1 option (the way I had it before), but of you select 2 it will only show 1 of the two, how can I make it show both options selected, here is the code:
<?php $makes = array("volvo","Saab","Opel","Audi","BMW") ?>
<form method="post" name="store" action="<?php $_SERVER['PHP_SELF'] ?>" >
<select multiple="multiple" name="cars">
<?php foreach ($makes as $make){echo "<option value=\"$make\">". $make ."</option>"; $vehicles = $_POST['cars'];} ?>
<input name="submit" type="submit">
</select>
</form>
<?php
if($_POST['submit']){
echo $vehicles;
}
?>
</body>
</html>
I hope I read this correctly that you would like to retrieve an array of results from the HTML multi select box.
By the way your code snippit is not correct; the HTML <form> closing tag should be after your closing <select> tag and I'm not sure why you have the following in your PHP for() loop:
$vehicles = $_POST['cars'];
You will want to make the HTML tags' name attribute an array as follows (Note I did not test this code):
<select multiple="multiple" name="cars[]">
<?php
foreach ($makes as $make) {
echo "<option value=\"$make\">". $make ."</option>";
}
?>
</select>
<?php
if($_POST['submit']) {
print_r($_POST['cars']);
}
?>
PHP.net - How do I get all the results from a select multiple HTML tag?
It isn't completely clear from your question but I think you mean the following bit of code only echoes one value:
if($_POST['submit']){
echo $vehicles;
}
To turn your selected cars into an array you need to add [] onto the end of the name:
<select multiple="multiple" name="cars[]">
Then to echo each of the selections you can use a foreach loop:
foreach ($_POST['cars'] as $car)
echo $car.'<br />';
you can try with if($_POST['submit']){
print_r($vehicles);
}
please let me know if any issue then..