Home>
I have been using PDO and bindValue to update the search system from multiple items in MySQL and PHP that I used before
If implemented, it will not work. I would appreciate your help.
Since the column item contains multiple characters, LIKE partial search is incorporated.
// search.php code
function getUserData ($params) {
// DB connection information
include_once ('database.php');
// Create DB connector
$Mysqli = new mysqli ($dsn, $usr, $passwd);
$Mysqli->set_charset ('utf8');
$query = "SELECT * FROM TABLE1";
// Check connection status
if ($Mysqli->connect_error) {
error_log ($Mysqli->connect_error);
exit;
}
// Generate SQl statement from entered search conditions
$where = [];
if (! empty ($params ['search_name'])) {
$where [] = "search_name like '% {$params [' search_name ']}%'";
}
if (! empty ($params ['color'])) {
$where [] = "color like '% {$params [' color ']}%'";
}
if (! empty ($params ['category'])) {
$where [] = "category like '% {$params [' category ']}%'";
}
if ($where) {
$whereSql = implode ("AND", $where);
$sql = "select * from TABLE1 where". $whereSql;
} else {
$sql = "select * from TABLE1";
}
$query. = $where;
// Execute SQL statement
$UserDataSet = $Mysqli->query ($sql);
// Change to a manageable form
$result = [];
while ($row = $UserDataSet->fetch_assoc ()) {
$result [] = $row;
}
return $result;
}// ー ー ー HTML side ー ー ー
<! doctype html>
<? php
include_once ('search.php');
$userData = getUserData ($_POST);
?>
<html>
<head>
</head>
<body>
// Search by 3 types: keyword search, check box, selection
<Input name = "search_name" value = "<? Php echo isset ($_ POST ['search_name'])? Htmlspecialchars ($_ POST ['search_name']): ''?>">
<input type = "checkbox" name = "color" value = "white"<? php echo isset ($_ POST ['color'])&&$_POST ['color'] == 'white'? 'selected': ' '? >><label for = "color">white</label>// other omitted
<Select name = "category">
<option value = "0"<? php echo empty ($_ POST ['category'])? 'selected': ''? >>Category A</option>// Other omitted
</select>
<button type = "submit" name = "search">Search</button>
*
// Display results as data other than above
<? php if (isset ($userData)):?>
<? php foreach ($userData as $row):?>
">
<? php echo htmlspecialchars ($row ['original_name'])?>
<? php endforeach;?>
<? php endif;?>
</body>
</html>
After revision
// search.php code
function getUserData () {
include_once ('database.php');
try {
$db = new PDO ($dsn, $usr, $passwd);
$db->setAttribute (PDO :: ATTR_ERRMODE, PDO :: ERRMODE_EXCEPTION);
$db->setAttribute (PDO :: ATTR_EMULATE_PREPARES, false);
$q = (string) filter_input (INPUT_GET, 'q');
$maxKeywords = -1;
$keywords = preg_split ('/ (?: \ p {Z} | \ p {Cc}) ++/u', $q, $maxKeywords, PREG_SPLIT_NO_EMPTY);
if ($keywords) {
foreach ($keywords as $keyword) {
$holders [] = "((search_name LIKE? ESCAPE '!') OR (color LIKE? ESCAPE '!') OR (category LIKE? ESCAPE '!'))";
$values [] = $values [] = '%'. preg_replace ('/ (? = [! _%]) /', '!', $keyword). '%';
}
$sql = "SELECT * FROM TABLE1 WHERE ('. implode (' AND ', $holders).')";
$UserDataSet = $bd->prepare ($sql);$UserDataSet->execute ($values);
$userData = $UserDataSet->fetchAll (PDO :: FETCH_ASSOC);
}
print 'Connection succeeded';
} catch (PDOException $e) {
header ('Content-Type: text/plain;charset = UTF-8', true, 500);
exit ('Could not connect'. $e->getMessage ());
}
function h ($str) {
return htmlspecialchars ($str, ENT_QUOTES, 'UTF-8');
}
}
// ー ー ー HTML side ー ー ー
<! doctype html>
<? php
include_once ('search.php');
$userData = getUserData ($_GET);
?>
<html>
<head>
</head>
<body>
// Search by 3 types: keyword search, check box, selection
<Input name = "search_name" value = "<? Php echo isset ($search_name)? = H ($search_name): ''?>">
<input type = "checkbox" name = "color" value = "white"<? php echo isset ($color)&&$color == 'white'? 'selected': ''? >><label for = "color ">White</label>// other omitted
<Select name = "category">
<option value = "0"<? php echo empty ($category)? 'selected': ''? >>Category A</option>// Other omitted
</select>
<button type = "submit" name = "search">Search</button>
*
≪Result display with data other than the column specified in // $holders []
<? php if (isset ($err)):?>
<p><? = h ($err->getMessage ());?></p>
<? php endif;?>
<? php if (0<count ($userData)):?>
<? php foreach ($userData as $row):?>
">
<? = h ($row ['original_name']);?>
<? php endforeach;?>
<? php endif;?>
</body>
</html>
-
Answer # 1
-
Answer # 2
regexp is easier to write
(However, escape processing is required when including regexp wildcards.) -
Answer # 3
For now, there is not enough data or information to check the operation, so only the points of interest
setAttribute (PDO :: ATTR_ERRMODE, PDO :: ERRMODE_EXCEPTION); $db->setAttribute (PDO :: ATTR_EMULATE_PREPARES, false); $q = filter_input (INPUT_GET, 'q'); $maxKeywords = -1; $keywords = preg_split ('/ (?: \ p {Z} | \ p {Cc}) ++/u', $q, $maxKeywords, PREG_SPLIT_NO_EMPTY); if (count ($keywords)>0) { $values = [];// add foreach ($keywords as $keyword) { $holders [] = "((search_name LIKE? ESCAPE '!') OR (color LIKE? ESCAPE '!') OR (category LIKE? ESCAPE '!'))"; // $values [] = $values [] = '%'. preg_replace ('/ (? = [! _%]) /', '!', $keyword). '%'; $values [] = '%'. preg_replace ('/ (? = [! _%]) /', '!', $keyword). '%'; } // $sql = "SELECT * FROM TABLE1 WHERE ('. implode (' AND ', $holders).')"; $sql = 'SELECT * FROM TABLE1 WHERE ('. implode ('AND', $holders). ')'; // $UserDataSet = $bd->prepare ($sql); $UserDataSet = $db->prepare ($sql); $UserDataSet->execute ($values); // $userData = $UserDataSet->fetchAll (PDO :: FETCH_ASSOC); return $UserDataSet->fetchAll (PDO :: FETCH_ASSOC); } // print 'Connection succeeded'; } catch (PDOException $e) { header ('Content-Type: text/plain;charset = UTF-8', true, 500); exit ('Could not connect'. $e->getMessage ()); } // function h ($str) // { // return htmlspecialchars ($str, ENT_QUOTES, 'UTF-8'); //} } function h ($str) { return htmlspecialchars ($str, ENT_QUOTES, 'UTF-8'); }
Related articles
- php - i am making a customer search system by studying, but i want to be able to connect to a database, but it does not work
- php - at the time of narrowing down search: i want to make a conditional branch when checking only parent terms or checking both
- php - in wordpress 1 i want to display only fixed pages and 2 search results excluding specific categories
- ruby - rails + aws + rds + mysql shortly describe partial match search (fuzzy search) for all columns
- about replacement with pandas "i want to search by partial match and replace all values"
- php vending machine system: i want to eliminate the undefined index error that appears when purchasing an unselected product wit
- taxonomy-i want to implement a refined search on my custom taxonomyphp page
- php - a system that supports images of a specified size
- php - i want to search wordpress in real time
- some files are not searched by glob function (file search) of php
- php - i want to get the number of search results (index number) of "site: ~" on google
- php - want to customize wordpress bbpress site search results
- java - i want to perform fuzzy search using bind variables
- php - i want to include a custom field in the search result with a check box in wordpress
- php - implementation of a search function for creating a fictitious ec site
- php - [laravel] i want to perform update and increment at the same time by sql operation
- php - how to search encrypted data and performance
- php - i don't want to be caught in the search when i get the data i want to do wherenot called rails with laravel
- java - i want to perform search evaluation of board games without using recursive expressions
- php - how can i narrow down the search to a fixed page?
Related questions
- javascript : How to connect a custom registration form to the database?
- How to correctly form a checkbox into a database array (Checkbox + Php + mysql)
- Templating an HTML file into PHP format
- Doesn't output ANGULAR PHP MVC data
- Link php and html
- php : Displaying items to users
- php : Pictures are duplicated when the page is refreshed
- php : How to organize the definition of a city correctly?
- php : Remove duplicate pages
- Cannot specify the link destination with an absolute path in PHP
Addition and correction request field
I'm still not sure to say, but
addcslashes
was misunderstood asaddslashes
, so removedIn the first place,
and
SQL is executed
$UserDataSet->execute ();
However, the SELECT statement is not executed because it is written after
return
.We recommend that you first understand the PDO behavior with the minimum functionality and code, referring to the PHP manual.
↑
$userDatais undefined
↑ The processing in foreach is probably not executed
↑
$stmt
is also undefined, so if the foreach process is executed, an error will occur