18.5 实战演练2——使用select语句查询数据信息
本案例讲述如何使用select语句查询数据信息,具体操作步骤如下。
01 在phpmysql文件夹下建立文件selectform.html,并且输入代码如下。
<html> <head> <title>Finding User</title> </head> <body> <h2>Finding users from mysql database.</h2> <form action="selectformhandler.php" method="post"> Select gender: <select name="gender"> <option value="male">man</option> <option value="female">woman</option> </select><br /> <input name="submit" type="submit" value="Find"/> </form> </body> </html>
02 在phpmysql文件夹下建立文件selectformhandler.php,并且输入代码如下。
<html> <head> <title>User found</title> </head> <body> <h2>User found from mysql database.</h2> <?php $gender = $_POST['gender']; if(!$gender){ echo "Error: There is no data passed."; exit; } if(!get_magic_quotes_gpc()){ $gender = addslashes($gender); } @ $db = mysqli_connect('localhost','root','753951'); mysqli_select_db($db,'adatabase'); if(mysqli_connect_errno()){ echo "Error: Could not connect to mysql database."; exit; } $q = "SELECT * FROM user WHERE gender = '".$gender."'"; $result = mysqli_query($db,$q); $rownum = mysqli_num_rows($result); for($i=0; $i<$rownum; $i++){ $row = mysqli_fetch_assoc($result); echo "Id:".$row['id']."<br />"; echo "Name:".$row['name']."<br />"; echo "Age:".$row['age']."<br />"; echo "Gender:".$row['gender']."<br />"; echo "Info:".$row['info']."<br />"; } mysqli_free_result($result); mysqli_close($db); ?> </body> </html>
03 运行selectform.html,结果如图18-7所示。
04 单击“Find”按钮,页面跳转至selectformhandler.php,并且返回信息如图18-8所示。
这样程序就给出了所有gender为female的用户信息。