我想學習如何動態生成一個基於用戶選擇填寫數據的表單字段的MySQL查詢。爲了使學習過程儘可能地簡單,我使用了一個帶有用戶名和姓氏字段的簡單表單。代碼的基本(非動態)版本如下:動態生成mysql的查詢與PHP
<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' ";
任何幫助(或如果有人能指點我一個很好的教程)將不勝感激!
謝謝!
請讀了[SQL注入](http://en.wikipedia.org/wiki/SQL_injection) – Kibbee