感谢stackoverflow.com的专家们,我设法创建了我的第一个php + mysql应用程序。 代码在mysql数据库中搜索姓氏和城市。通过两个下拉列表进行选择:
选择城市:
所有城市
利物浦
曼彻斯特
选择姓氏:
所有姓氏为
列侬
Gallagher的
代码将返回例如。所有住在利物浦的Lennons。
但是,我无法使“所有城市”和“所有姓氏”选项生效,以便代码返回例如。生活在任何城市的所有Lennons或生活在利物浦的所有人。那么,怎么做呢?
到目前为止的代码:
的index.php
<?php
$conn = mysql_connect('localhost', 'user', 'password') or die("Connection failed");
mysql_select_db("database", $conn) or die("Switch database failed");
//this gets the cities from the database to the drop list
$query = "SELECT DISTINCT city FROM user".mysql_real_escape_string($city);
$result = mysql_query($query, $conn);
$options="";
while ($row=mysql_fetch_array($result)) {
$city=$row["city"];
$options.="<OPTION VALUE=\"$city\">".$city;
}
//this gets the last names from the database to the drop list
$query2 = "SELECT DISTINCT lastname FROM user".mysql_real_escape_string($lastname);
$result2 = mysql_query($query2, $conn);
$options2="";
while ($row2=mysql_fetch_array($result2)) {
$lastname=$row2["lastname"];
$options2.="<OPTION VALUE=\"$lastname\">".$lastname;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>test</title>
</head>
<body>
<form action="get.php" method="post">
<p>
<select name="city">
<option value=0>Choose
<option value=1>All cities
<?=$options?>
</select>
</p>
<p>
<select name="lastname">
<option value=0>Choose
<option value=1>All last names
<?=$options2?>
</select>
</p>
<p>
<input value="Search" type="submit">
</p>
</form>
<br>
</body>
</html>
get.php
<?php
$conn = mysql_connect('localhost', 'user', 'password') or die("Connection failed");
mysql_select_db("database", $conn) or die("Switch database failed");
$query = "SELECT * FROM user WHERE city = '".mysql_real_escape_string($_POST['city'])."' AND lastname = '".mysql_real_escape_string($_POST['lastname'])."'";
$result = mysql_query($query, $conn);
echo $rowcount;
$zerorows=true;
while ($row = mysql_fetch_assoc($result))
{
$zerorows=false;
echo '<b>City: </b>'.htmlspecialchars($row[city]).'<br />';
echo '<b>Last name: </b>'.htmlspecialchars($row[lastname]).'<br />';
echo '<b>Information: </b>'.htmlspecialchars($row[information]).'<br />'.'<br />';
}
if($zerorows) echo "No results";
mysql_close($conn);
?>
答案 0 :(得分:1)
为所有人设置一个特殊值(例如ALL)并输入:
if ($_POST['city'] == 'ALL')
{
$sql_city = '1';
}
else
{
$sql_city = "city = '".mysql_real_escape_string($_POST['city'])."'";
}
if ($_POST['lastname'] == 'ALL')
{
$sql_lastname = '1';
}
else
{
$sql_lastname = "lastname = '".mysql_real_escape_string($_POST['lastname'])."'";
}
$query = "SELECT * FROM user WHERE ".$sql_city." AND '".$sql_lastname."";
然后根据if构建SQL语句。你使用1的原因是它总是评估为真。