php mysql search using boxlist

933

I am looking for a way to search for data from the database using input type box list, I tried make the code but it doesn't display anything:

html code:

<form action="users.php" method="post" name="searching">  
<select name="users">
<option selected value="">-- select --</option>
<option value="1">user1</option>
<option value="2">user2</option>
<option value="3">user3</option>        
</select>
<input type="submit" name="search" value="find">  
</form>  


php code:

if (isset($_POST['users'])) {
$key = trim ($_POST['users']);
$s = "SELECT * FROM users where user_name LIKE '%$key %'";
$res = mysql_query($s) or die('query did not work');
while($row = mysql_fetch_array( $res )) 
{ 
?>
User ID: <?php echo $row['user_id'] ?>
User Name: <?php echo $row['user_name'] ?> 

<?php
}
?>

when I try the code I didn't get any result and when I remove the while loop and put this instead of it :

<?php echo $key; ?>

it gives me the numbers of the selected value, for example if I select user2 the result will be 2. and I want the result to be user id and user name.

645

Answer

Solution:

you need to fetch all the user name in your drop down select box

<select name="users">
<option selected value="">-- select --</option>
<?php $s2 = "SELECT * FROM users";
$q2=mysql_query($s2) or die($s2);
while($rw=mysql_fetch_array($q2))
{ 
echo '<option value="'.$rw['userid'].'">'.$rw['username'].'</option>';
}</select>
?>

<?php if (isset($_POST['search'])) {  // submit button name here
$key = $_POST['users'];
$s = "SELECT * FROM users where user_id='".$key."'";
$res = mysql_query($s) or die($s);
while($row = mysql_fetch_array( $res )) 
{ 
?>
User ID: <?php echo $row['user_id'] ?>
User Name: <?php echo $row['user_name'] ?> 
<?php
}
?>
103

Answer

Solution:

edit your html to this,you will get the in $_POST which will be in value='something'

<form action="users.php" method="post" name="searching">  
<select name="users">
<option selected value="">-- select --</option>
<option value="user1">user1</option>
<option value="user2">user2</option>
<option value="user3">user3</option>        
</select>
<input type="submit" name="search" value="find">  
</form>

Or if value is the id of user then change query to this

$s = "SELECT * FROM users where user_id='".$key."'";

People are also looking for solutions to the problem: php - Joomla 3! Module Parameters

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.