Home Backend Development PHP Problem Implementation method of php keyword query

Implementation method of php keyword query

Nov 02, 2020 am 11:46 AM
php

How to implement keyword query in php: first obtain user input; then decompose multiple keywords entered by the user and store them in an array; then construct an SQL statement based on multiple keywords; and finally sort the search results , and display the current search results.

Implementation method of php keyword query

Recommended: "PHP Video Tutorial"

PHP searches the database mainly by using like in the SQL statement clause to achieve. If you search for multiple keywords at the same time, you can use the union clause to combine the search results. The following code implements a search page.

Quote

<?php require_once(&#39;&#39;Connections/conn.php&#39;&#39;); ?>
<?php
$colname_rs = $_GET[&#39;&#39;key&#39;&#39;]; //获得用户输入
$result = explode(&#39;&#39;,&#39;&#39;,$_GET[&#39;&#39;key&#39;&#39;]);//分解用户输入的多个关键词,存入$result数组
mysql_select_db($database_conn, $conn); //连接数据库
//根据多个关键词构建SQL语句
$query_rs = "SELECT * FROM (";
for($i=0;$i<count($result);$i++) //根据每个搜索关键词构建SQL语句
{
if($i==0) //对第一个关键词,不使用UNION
$query_rs .= "SELECT * FROM searchtable WHERE title LIKE &#39;&#39;%$result[0]%&#39;&#39;
OR content LIKE &#39;&#39;%$result[0]%&#39;&#39;";
else //对其他关键词,使用UNION连接
$query_rs .= " UNION SELECT * FROM searchtable WHERE title LIKE
&#39;&#39;%$result[$i]%&#39;&#39; OR content LIKE &#39;&#39;%$result[$i]%&#39;&#39;";
}
$query_rs .= ") T ORDER BY last_access DESC"; //对搜索结果排序
//执行SQL语句
$rs = mysql_query($query_rs, $conn) or die(mysql_error());
$row_rs = mysql_fetch_assoc($rs);
$totalRows_rs = mysql_num_rows($rs);
?>
<html>
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<form name="form1" method="get" action="?">
<div align="center">请输入要搜索关键词:
<input name="key" type="text" size="64" value="<?php echo $_GET[&#39;&#39;key&#39;&#39;] ?>">
<input type="submit" value="Submit">
</div>
</form>
<p align="center"><B>当前关键词:
<?php
for($i=0;$i<count($result);$i++) { //循环显示关键词
echo $result[$i]." ";
}
?></B></p>
<p><hr></p>
<?php if($totalRows_rs>0) do { //显示当前搜索结果 ?>
<p>* <a href="show.php?key=<?php echo $colname_rs ?>&id=<?php echo
$row_rs[&#39;&#39;id&#39;&#39;]; ?>"><?php echo $row_rs[&#39;&#39;title&#39;&#39;]; ?></a>(<?php echo
$row_rs[&#39;&#39;click&#39;&#39;]; ?> | <?php echo $row_rs[&#39;&#39;last_access&#39;&#39;]; ?>)</p>
<?php } while ($row_rs = mysql_fetch_assoc($rs)); ?>
</body>
</html>
<?php
mysql_free_result($rs);
?>

Here, you can use English commas "," on the page to search for multiple keywords.

Here, the connection with the database is still placed in a special PHP file to facilitate later modifications.

The above is the detailed content of Implementation method of php keyword query. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1596
276
edge pdf viewer not working edge pdf viewer not working Aug 07, 2025 pm 04:36 PM

TestthePDFinanotherapptodetermineiftheissueiswiththefileorEdge.2.Enablethebuilt-inPDFviewerbyturningoff"AlwaysopenPDFfilesexternally"and"DownloadPDFfiles"inEdgesettings.3.Clearbrowsingdataincludingcookiesandcachedfilestoresolveren

VS Code shortcut to focus on explorer panel VS Code shortcut to focus on explorer panel Aug 08, 2025 am 04:00 AM

In VSCode, you can quickly switch the panel and editing area through shortcut keys. To jump to the left Explorer panel, use Ctrl Shift E (Windows/Linux) or Cmd Shift E (Mac); return to the editing area to use Ctrl ` or Esc or Ctrl 1~9. Compared to mouse operation, keyboard shortcuts are more efficient and do not interrupt the encoding rhythm. Other tips include: Ctrl KCtrl E Focus Search Box, F2 Rename File, Delete File, Enter Open File, Arrow Key Expand/Collapse Folder.

Fixed: Windows Update Failed to Install Fixed: Windows Update Failed to Install Aug 08, 2025 pm 04:16 PM

RuntheWindowsUpdateTroubleshooterviaSettings>Update&Security>Troubleshoottoautomaticallyfixcommonissues.2.ResetWindowsUpdatecomponentsbystoppingrelatedservices,renamingtheSoftwareDistributionandCatroot2folders,thenrestartingtheservicestocle

Compare and contrast PHP Traits, Abstract Classes, and Interfaces with practical use cases. Compare and contrast PHP Traits, Abstract Classes, and Interfaces with practical use cases. Aug 11, 2025 pm 11:17 PM

Useinterfacestodefinecontractsforunrelatedclasses,ensuringtheyimplementspecificmethods;2.Useabstractclassestosharecommonlogicamongrelatedclasseswhileenforcinginheritance;3.Usetraitstoreuseutilitycodeacrossunrelatedclasseswithoutinheritance,promotingD

Fix: Ethernet 'Unidentified Network' Fix: Ethernet 'Unidentified Network' Aug 12, 2025 pm 01:53 PM

Restartyourrouterandcomputertoresolvetemporaryglitches.2.RuntheNetworkTroubleshooterviathesystemtraytoautomaticallyfixcommonissues.3.RenewtheIPaddressusingCommandPromptasadministratorbyrunningipconfig/release,ipconfig/renew,netshwinsockreset,andnetsh

How to work with arrays in php How to work with arrays in php Aug 20, 2025 pm 07:01 PM

PHParrayshandledatacollectionsefficientlyusingindexedorassociativestructures;theyarecreatedwitharray()or[],accessedviakeys,modifiedbyassignment,iteratedwithforeach,andmanipulatedusingfunctionslikecount(),in_array(),array_key_exists(),array_push(),arr

Mastering Flow Control Within foreach Using break, continue, and goto Mastering Flow Control Within foreach Using break, continue, and goto Aug 06, 2025 pm 02:14 PM

breakexitstheloopimmediatelyafterfindingatarget,idealforstoppingatthefirstmatch.2.continueskipsthecurrentiteration,usefulforfilteringitemsliketemporaryfiles.3.gotojumpstoalabeledstatement,acceptableinrarecaseslikecleanuporerrorhandlingbutshouldbeused

Describe the Observer design pattern and its implementation in PHP. Describe the Observer design pattern and its implementation in PHP. Aug 15, 2025 pm 01:54 PM

TheObserverdesignpatternenablesautomaticnotificationofdependentobjectswhenasubject'sstatechanges.1)Itdefinesaone-to-manydependencybetweenobjects;2)Thesubjectmaintainsalistofobserversandnotifiesthemviaacommoninterface;3)Observersimplementanupdatemetho

See all articles