0

我正在寻找一种使用输入类型框列表从数据库中搜索数据的方法,我尝试制作代码但它没有显示任何内容:

html code:

<form action="users.php" method="post" name="searching">  
<select name="users">
<option selected="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
}
?>

当我尝试代码时,我没有得到任何结果,当我删除 while 循环并用它代替它时:

<?php echo $key; ?>

它给了我所选值的数字,例如,如果我选择 user2,结果将是 2。我希望结果是用户 ID 和用户名。

4

2 回答 2

1

将您的 html 编辑为此,您将在 $_POST 中获得 value='something'

<form action="users.php" method="post" name="searching">  
<select name="users">
<option selected="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>

或者,如果 value 是用户的 id,则将查询更改为此

$s = "SELECT * FROM users where user_id='".$key."'";
于 2013-09-06T10:53:45.920 回答
0

您需要在下拉选择框中获取所有用户名

<select name="users">
<option selected="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
}
?>
于 2013-09-06T10:51:24.370 回答