Collections:
Build WHERE Criteria with Web Form Data in MySQL
How To Build WHERE Criteria with Web Form Search Fields in MySQL?
✍: FYIcenter.com
If your PHP script is linked to a Web form which takes search key words for multiple data fields. For example, your Web form asks your visitor to search for Website links with a URL search field, a Website title search field, a description search field, and a comment search field.
Now you have to build a nice WHERE criteria string that meets the following requirements:
The tutorial script below shows you a good sample that meets the above requirements:
<?php
$_REQUEST = array("title"=>" Joe's brother\'s ",
"description"=>"c:\windows\system ",
"comment"=>" best ");
$sql = "SELECT * FROM siteLinks WHERE 1=1";
$url = getFormParam("url");
$title = getFormParam("title");
$description = getFormParam("description");
$comment = getFormParam("comment");
if (strlen($url) > 0)
$sql .= " AND url LIKE '%".$url."%'";
if (strlen($title) > 0)
$sql .= " AND title LIKE '%".$title."%'";
if (strlen($description) > 0)
$sql .= " AND description LIKE '%".$description."%'";
if (strlen($comment) > 0)
$sql .= " AND comment LIKE '%".$comment."%'";
print("SQL statement:\n");
print($sql."\n");
function getFormParam($p) {
if (isset($_REQUEST[$p])) {
return str_replace("\\", "\\\\",
str_replace("'", "''",
trim($_REQUEST[$p])));
} else {
return "";
}
}
?>
If you run this script, you will get something like this:
SQL statement: SELECT * FROM siteLinks WHERE 1=1 AND title LIKE '%Joe''s brother\\''s%' AND description LIKE '%c:\\windows\\system%' AND comment LIKE '%best%'
You should learn a couple of things in this script:
⇒ Query Multiple Tables Jointly in MySQL
⇐ Key Word Search in Tables in MySQL
2017-06-23, 2416🔥, 0💬
Popular Posts:
How To Create a Dynamic Cursor with the DYNAMIC Option in SQL Server Transact-SQL? If the underlying...
How To Drop a Stored Procedure in Oracle? If there is an existing stored procedure and you don't wan...
How To Use "IF ... ELSE IF ..." Statement Structures in SQL Server Transact-SQL? "IF ... ELSE IF ......
What Happens If the UPDATE Subquery Returns Multiple Rows in MySQL? If a subquery is used in a UPDAT...
How To Format Time Zone in +/-hh:mm Format in SQL Server Transact-SQL? From the previous tutorial, y...