我正在尝试学习如何根据用户选择填充数据的表单字段动态生成 mysql 查询。为了使学习过程尽可能简单,我使用了一个简单的表单,其中包含用户名字和姓氏的字段。代码的基本(非动态)版本如下:
<html>
<head>
<title>Untitled</title>
</head>
<body>
<form method="post" name="test" action="dynamic_search.php">
<input type="text" name="first_name">
<input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
<?php
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
include "link.php";
$query = "SELECT * FROM members " .
"WHERE first_name = '$first_name' " .
"AND last_name = '$last_name' ";
$result = mysql_query($query)
or die(mysql_error());
$row = mysql_fetch_array($result);
$member_id = $row['member_id'];
$member_first_name = $row['first_name'];
$member_last_name = $row['last_name'];
echo $member_id;
echo $member_first_name;
echo $member_last_name;
?>
</body>
</html>
我需要做的是根据提交的数据生成查询。因此,如果用户只输入他们的名字,查询将显示为:
$query = "SELECT * FROM members " .
"WHERE first_name = '$first_name' ";
但是,如果用户同时输入他们的名字和姓氏,则查询将显示为:
$query = "SELECT * FROM members " .
"WHERE first_name = '$first_name' " .
"AND last_name = '$last_name' ";
任何帮助(或者如果有人可以为我指出一个好的教程)将不胜感激!
谢谢!