使用多个html字段搜索mysql

时间:2014-04-02 05:16:24

标签: php mysql

如何使用html,php和mysql向搜索数据库添加多个字段?

这是HTML代码。 我想在搜索数据库中添加更多字段选项,以获取名字,年龄,性别。 示例:搜索[first name]和/或[Age]和/或[gender]

<h2>Search</h2> 
 <form name="search" action="searchresults.php" method="POST">
 Seach for: <input type="text" name="find" /> in 
 <Select NAME="field">
 <Option VALUE="firstName">First Name</option>
 <Option VALUE="lastName">Last Name</option>
 <Option VALUE="email">email</option>
 </Select>
 <input type="hidden" name="searching" value="yes" />
 <input type="submit" name="search" value="Search" />
 </form>

这是PHP。

数据库连接

$find = strtoupper($find); 
$find = strip_tags($find); 
$find = trim ($find); 


$find=$_POST['find'];
$field=$_POST['field'];

$data="SELECT firstName, lastName, email, userphoto, age FROM contactInfo WHERE     upper($field) LIKE '%$find%'"; 

$result = mysql_query($data);
$count=mysql_numrows($result);

echo '<br><br>';

if($count > 0){

echo"<table border=0>";

//get images and names in two arrays
$firstName= $row["firstName"];
$lastName= $row["lastName"];
$email= $row["email"]; 
$userphoto= $row["userphoto"];
$age= $row["age"];

$age = array();
$userphoto = array();
$firstName = array();
$lastName = array();

while ($row = mysql_fetch_array($result))
{
$userphoto[] = "<img src='images/".$row['userphoto']."' height='200' width='175'>";
$firstName[] = $row['firstName'];
$lastName[] = $row['lastName'];
$age[] = $row['age'];
$email[] = $row['email'];
}

while(!empty($userphoto))
{       
//output images     
foreach(array($userphoto, $firstName, $lastName, $age, $email) as $items)
{
    echo "<tr>";
    foreach($items as $key=>$item)
    {
        echo "<td><font size =\"3\" >$item</td>";              
        //output only four of them
        if($key==4)
        {
            break;
        }
    }
    echo "</tr>";
}
//remove the first five images from $images because they're already printed
$userphoto = array_slice($userphoto, 5);
$firstName = array_slice($firstName, 5);
$lastName= array_slice($lastName, 5);
$email = array_slice($email, 5);
$age = array_slice($age, 5);
}
echo"</table>";

2 个答案:

答案 0 :(得分:0)

更改您的查询。

$data="SELECT firstName, lastName, email, userphoto, age FROM contactInfo WHERE `".$field."` LIKE '%".$find."%'"; 

答案 1 :(得分:0)

我将查询分为两部分:

首先创建一个静态部分:

$query = "SELECT firstName, lastName, email, userphoto, age FROM contactInfo WHERE"

然后计算了dinamic部分:

  • 对于每个字段,用户根据和/或选项选择:

$query = $query . $nameField . ("and" || "or") . $valueField