如何在同一页面展示PHP+MySQL数据库搜索结果?
如何让PHP+MySQL搜索结果显示在同一页面?
要实现搜索结果在同一页面展示,核心是把表单提交目标设为当前页面,并将查询逻辑整合到这个页面中,仅在表单提交时执行查询并渲染结果。下面是修改后的完整代码和关键说明:
修改后的完整代码
<html> <head> <title>Digital Library</title> </head> <body> <br /> <center> <img src="logo.png"></img> <h1>Digital Library</h1> <h3>Enter Company Name</h3> <!-- 将表单提交目标设为当前页面,留空则默认提交到当前URL --> <form action="" method="post"> <input type="text" name="term" /> <br /> <input type="submit" name="submit" value="Submit" align="center" /> </form> <!-- 搜索结果展示区域 --> <?php // 仅当表单提交(存在submit参数)时才执行查询逻辑 if(isset($_POST['submit'])){ // 注意:mysql扩展已在PHP7+彻底废弃,建议尽快迁移到mysqli或PDO mysql_connect("localhost", "root","") or die(mysql_error()); mysql_select_db("vdl"); // 转义用户输入,避免基础SQL注入风险(更安全的方式是用预处理语句) $term = mysql_real_escape_string($_POST['term']); $sql = mysql_query("select * from digital_library where company_name like '%$term%'"); // 判断是否有匹配结果 if(mysql_num_rows($sql) > 0){ while ($row = mysql_fetch_array($sql)){ echo "<strong>Company Name:</strong> ".$row['company_name']."<br>"; echo "<strong> Since: </strong> ".$row['since']."<br>"; echo "<strong> Strength: </strong> ".$row['strength']."<br>"; echo "<strong> Head Quarters: </strong> ".$row['head_quarter']."<br>"; echo "<strong> Location (City): </strong> ".$row['locations']."<br>"; echo "<strong> Development Centers: </strong> ".$row['development_centers']."<br>"; echo "<strong> Customers: </strong> ".$row['customers']."<br>"; echo "<strong> MNC: </strong> ".$row['mnc']."<br>"; echo "<strong> CMMI: </strong> ".$row['cmmi']."<br>"; echo "<strong> Domains: </strong> ".$row['domains']."<br>"; echo "<strong> Industries: </strong> ".$row['industries']."<br>"; echo "<strong> Domain Competitors: </strong> ".$row['domain_competitor']."<br>"; echo "<strong> Products: </strong> ".$row['products']."<br>"; echo "<strong> Services: </strong> ".$row['services']."<br>"; echo "<strong> Uniqueness: </strong> ".$row['uniqueness']."<br>"; echo "<strong> URL: </strong> ".$row['url']."<br>"; echo "<strong> Onsights: </strong> ".$row['onsight']."<br>"; echo "<strong> Benefits: </strong> ".$row['benefits']."<br>"; echo "<strong> Awards: </strong> ".$row['awards']."<br>"; echo '<br/><br/>'; } } else { echo "<p>No results found for your search term.</p>"; } } ?> </center> </body> </html>
关键修改点说明
- 表单提交目标调整:把
<form>的action属性留空(或设为<?php echo $_SERVER['PHP_SELF']; ?>),这样表单会提交到当前页面,而非跳转到search.php。 - 条件执行查询:用
if(isset($_POST['submit']))包裹PHP查询代码,确保只有用户点击提交按钮后,才会执行数据库查询和结果展示,避免页面初始加载时就执行无用查询。 - 结果位置布局:将结果展示的PHP代码放在表单下方,提交后结果会直接显示在表单下方的同一页面区域内。
重要注意事项
- 废弃扩展提醒:你当前使用的
mysql_*函数已在PHP7.0及以上版本被移除,建议尽快迁移到mysqli_*或PDO,避免后续版本兼容性问题。 - SQL注入防护:直接拼接用户输入到SQL语句存在严重注入风险,上述代码用
mysql_real_escape_string做了基础防护,但更安全的方案是使用预处理语句(mysqli/PDO均支持)。 - 输入优化:可以增加输入验证逻辑(比如检查输入是否为空),提升用户体验和系统安全性。
内容的提问来源于stack exchange,提问作者user9740150
相关产品推荐
相关产品推荐

