Reputation: 114
I have a mysql database of games that you can hire. I created a query in php so that the user is able to type in a title or game description and the result will be shown in a table as a simple list. However, I want to display the results of my array in a drop down. But how? I've tried to apply code snippets I've found online(including Stack Overflow) but failed miserably to make them work. Any help would be most appreciated.
<table>
<tr>
<td>Game ID</td>
<td>Game Name</td>
<td>Game Description</td>
</tr>
<?php
if(isset($_REQUEST['submit'])){
$search=$_POST['search'];
$sql="SELECT* FROM gamestbl WHERE game_name LIKE '%{$search}%' OR game_description LIKE '%{$search}%'";
$q=mysqli_query($conn,$sql);
while($res=mysqli_fetch_array($q)){
?>
<tr>
<td><?php echo $res['game_id'];?></td>
<td><?php echo $res['game_name'];?></td>
<td><?php echo $res['game_description'];?></td>
</tr>
<?php }
}?>
</table>
Upvotes: 0
Views: 64
Reputation:
Replace your table with select:
<select name="game">
<?php
if(isset($_REQUEST['submit'])){
$search=$_POST['search'];
$sql="SELECT* FROM gamestbl WHERE game_name LIKE '%{$search}%' OR game_description LIKE '%{$search}%'";
$q=mysqli_query($conn,$sql);
while($res=mysqli_fetch_array($q)){
?>
<option value="<?php echo $res['game_id'];?>"><?php echo $res['game_name'];?></option>
<?php }
}?>
</select>
Upvotes: 2
Reputation: 29278
This is a pretty common problem, and you've got the right idea. Right now, you're populating these into a <table>
element's <tr>
and <td>
elements. So, why not change that to a <select>
and <option>
layout?
Here's the basic idea. During your while loop, echo an <option>
for each game. Set the value
attribute to the game's id and it's display to the game's name and description.:
<option value="<?php echo $res["game_id"]; ?>"><?php $res["game_name"]."-".$res["game_description"]; ?></option>
Like you have with your <table>
, make sure to define the <select>
outside of the php while
loop, or you'll end up with multiple dropdowns.
Hope that helps!
Upvotes: 2