SQL parameterized query with LIKE '% ? %' PHP - php

I have a Search function in php and have created it using a parameterized query to make it secure.
$words = $_POST['words']//words is the form that has the words submitted by the user
$array = explode(',', $words);
$con = mysqli_connect("localhost","user","pass","database");
$stmt = $con->prepare(" SELECT column_name FROM table WHERE column_name LIKE ?")
foreach($array as $key) { //searches each word and displays results
$stmt->bind_param('s', $key)
$stmt->execute();
$result = $stmt->get-result();
while($row = $result->fetch_assoc(){
echo $row["column_name"]
}
}
however I want $stmt statement to be
$stmt = $con->prepare(" SELECT column_name FROM table WHERE column_name LIKE '%?%' ")
otherwise people have to type in the entire value of column_name to find it.

You can use CONCAT(), like this:
LIKE CONCAT ('%', ?, '%')

You can do this as follows:
$key="%$key%"
Then bind $key.
Also see PHP Binding a Wildcard for pretty much the same question....

Related

MySQL PHP loop search query [duplicate]

Here's my attempt at it:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE "?%"');
$query->execute(array('value'));
while ($results = $query->fetch())
{
echo $results['column'];
}
Figured it out right after I posted:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->execute(array('value%'));
while ($results = $query->fetch())
{
echo $results['column'];
}
For those using named parameters, here's how to use LIKE with % partial matching for MySQL databases: WHERE column_name LIKE CONCAT('%', :dangerousstring, '%')
where the named parameter is :dangerousstring.
In other words, use explicitly unescaped % signs in your own query that are separated and definitely not the user input.
Edit: Concatenation syntax for Oracle databases uses the concatenation operator: ||, so it'll simply become:
WHERE column_name LIKE '%' || :dangerousstring || '%'
However there are caveats as #bobince mentions here that:
The
difficulty
comes when you want to allow a literal % or _ character in the
search string, without having it act as a wildcard.
So that's something else to watch out for when combining like and parameterization.
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->bindValue(1, "%$value%", PDO::PARAM_STR);
$query->execute();
if (!$query->rowCount() == 0)
{
while ($results = $query->fetch())
{
echo $results['column'] . "<br />\n";
}
}
else
{
echo 'Nothing found';
}
You can also try this one. I face similar problem but got result after research.
$query = $pdo_connection->prepare('SELECT * FROM table WHERE column LIKE :search');
$stmt= $pdo_connection->prepare($query);
$stmt->execute(array(':search' => '%'.$search_term.'%'));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
This works:
search `table` where `column` like concat('%', :column, '%')
I got this from php delusions
$search = "%$search%";
$stmt = $pdo->prepare("SELECT * FROM table WHERE name LIKE ?");
$stmt->execute([$search]);
$data = $stmt->fetchAll();
And it works for me, very simple. Like he says , you have to "prepare our complete literal first" before sending it to the query
PDO escapes "%" (May lead to sql injection): The use of the previous code will give the desire results when looking to match partial strings BUT if a visitor types the character "%" you will still get results even if you don't have anything stored in the data base (it may lead sql injections)
I've tried a lot of variation all with the same result PDO is escaping "%" leading unwanted/unexcited search results.
I though it was worth sharing if anyone has found a word around it please share it
I had a similar need but was using a variable grabbed from a form. I did it like this to get results from my PostgreSQL DB, using PHP:
<?php
$player = $_POST['search']; //variable from my search form
$find = $sqlPDO->prepare("SELECT player FROM salaries WHERE player ILIKE ?;");
$find->execute(['%'.$player.'%']);
while ($row = $find->fetch()) {
echo $row['player']."</br>";
}
?>
The "ILIKE" makes the search non-case sensitive, so a search for cart or Cart or cARt will all return the same results.
The only way I could get this to work was to put the %$search% into another variable.
if(isset($_POST['submit-search'])){
$search = $_POST['search'];
}
$query = 'SELECT * FROM posts WHERE post_title LIKE :search';
$value ="%$search%";
$stmt= $pdo->prepare($query);
$stmt->execute(array(':search' => $value));
I don't know if this is the best way to do it, in the while loop I used:
while ($r = $stmt->fetch(PDO::FETCH_ASSOC)){

how to use PDO prepared statements in PHP with SQL LIKE operator [duplicate]

Here's my attempt at it:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE "?%"');
$query->execute(array('value'));
while ($results = $query->fetch())
{
echo $results['column'];
}
Figured it out right after I posted:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->execute(array('value%'));
while ($results = $query->fetch())
{
echo $results['column'];
}
For those using named parameters, here's how to use LIKE with % partial matching for MySQL databases: WHERE column_name LIKE CONCAT('%', :dangerousstring, '%')
where the named parameter is :dangerousstring.
In other words, use explicitly unescaped % signs in your own query that are separated and definitely not the user input.
Edit: Concatenation syntax for Oracle databases uses the concatenation operator: ||, so it'll simply become:
WHERE column_name LIKE '%' || :dangerousstring || '%'
However there are caveats as #bobince mentions here that:
The
difficulty
comes when you want to allow a literal % or _ character in the
search string, without having it act as a wildcard.
So that's something else to watch out for when combining like and parameterization.
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->bindValue(1, "%$value%", PDO::PARAM_STR);
$query->execute();
if (!$query->rowCount() == 0)
{
while ($results = $query->fetch())
{
echo $results['column'] . "<br />\n";
}
}
else
{
echo 'Nothing found';
}
You can also try this one. I face similar problem but got result after research.
$query = $pdo_connection->prepare('SELECT * FROM table WHERE column LIKE :search');
$stmt= $pdo_connection->prepare($query);
$stmt->execute(array(':search' => '%'.$search_term.'%'));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
This works:
search `table` where `column` like concat('%', :column, '%')
I got this from php delusions
$search = "%$search%";
$stmt = $pdo->prepare("SELECT * FROM table WHERE name LIKE ?");
$stmt->execute([$search]);
$data = $stmt->fetchAll();
And it works for me, very simple. Like he says , you have to "prepare our complete literal first" before sending it to the query
PDO escapes "%" (May lead to sql injection): The use of the previous code will give the desire results when looking to match partial strings BUT if a visitor types the character "%" you will still get results even if you don't have anything stored in the data base (it may lead sql injections)
I've tried a lot of variation all with the same result PDO is escaping "%" leading unwanted/unexcited search results.
I though it was worth sharing if anyone has found a word around it please share it
I had a similar need but was using a variable grabbed from a form. I did it like this to get results from my PostgreSQL DB, using PHP:
<?php
$player = $_POST['search']; //variable from my search form
$find = $sqlPDO->prepare("SELECT player FROM salaries WHERE player ILIKE ?;");
$find->execute(['%'.$player.'%']);
while ($row = $find->fetch()) {
echo $row['player']."</br>";
}
?>
The "ILIKE" makes the search non-case sensitive, so a search for cart or Cart or cARt will all return the same results.
The only way I could get this to work was to put the %$search% into another variable.
if(isset($_POST['submit-search'])){
$search = $_POST['search'];
}
$query = 'SELECT * FROM posts WHERE post_title LIKE :search';
$value ="%$search%";
$stmt= $pdo->prepare($query);
$stmt->execute(array(':search' => $value));
I don't know if this is the best way to do it, in the while loop I used:
while ($r = $stmt->fetch(PDO::FETCH_ASSOC)){

Select records using PDO with where clause in PHP [duplicate]

Here's my attempt at it:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE "?%"');
$query->execute(array('value'));
while ($results = $query->fetch())
{
echo $results['column'];
}
Figured it out right after I posted:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->execute(array('value%'));
while ($results = $query->fetch())
{
echo $results['column'];
}
For those using named parameters, here's how to use LIKE with % partial matching for MySQL databases: WHERE column_name LIKE CONCAT('%', :dangerousstring, '%')
where the named parameter is :dangerousstring.
In other words, use explicitly unescaped % signs in your own query that are separated and definitely not the user input.
Edit: Concatenation syntax for Oracle databases uses the concatenation operator: ||, so it'll simply become:
WHERE column_name LIKE '%' || :dangerousstring || '%'
However there are caveats as #bobince mentions here that:
The
difficulty
comes when you want to allow a literal % or _ character in the
search string, without having it act as a wildcard.
So that's something else to watch out for when combining like and parameterization.
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->bindValue(1, "%$value%", PDO::PARAM_STR);
$query->execute();
if (!$query->rowCount() == 0)
{
while ($results = $query->fetch())
{
echo $results['column'] . "<br />\n";
}
}
else
{
echo 'Nothing found';
}
You can also try this one. I face similar problem but got result after research.
$query = $pdo_connection->prepare('SELECT * FROM table WHERE column LIKE :search');
$stmt= $pdo_connection->prepare($query);
$stmt->execute(array(':search' => '%'.$search_term.'%'));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
This works:
search `table` where `column` like concat('%', :column, '%')
I got this from php delusions
$search = "%$search%";
$stmt = $pdo->prepare("SELECT * FROM table WHERE name LIKE ?");
$stmt->execute([$search]);
$data = $stmt->fetchAll();
And it works for me, very simple. Like he says , you have to "prepare our complete literal first" before sending it to the query
PDO escapes "%" (May lead to sql injection): The use of the previous code will give the desire results when looking to match partial strings BUT if a visitor types the character "%" you will still get results even if you don't have anything stored in the data base (it may lead sql injections)
I've tried a lot of variation all with the same result PDO is escaping "%" leading unwanted/unexcited search results.
I though it was worth sharing if anyone has found a word around it please share it
I had a similar need but was using a variable grabbed from a form. I did it like this to get results from my PostgreSQL DB, using PHP:
<?php
$player = $_POST['search']; //variable from my search form
$find = $sqlPDO->prepare("SELECT player FROM salaries WHERE player ILIKE ?;");
$find->execute(['%'.$player.'%']);
while ($row = $find->fetch()) {
echo $row['player']."</br>";
}
?>
The "ILIKE" makes the search non-case sensitive, so a search for cart or Cart or cARt will all return the same results.
The only way I could get this to work was to put the %$search% into another variable.
if(isset($_POST['submit-search'])){
$search = $_POST['search'];
}
$query = 'SELECT * FROM posts WHERE post_title LIKE :search';
$value ="%$search%";
$stmt= $pdo->prepare($query);
$stmt->execute(array(':search' => $value));
I don't know if this is the best way to do it, in the while loop I used:
while ($r = $stmt->fetch(PDO::FETCH_ASSOC)){

implement LIKE query in PDO

I am running problems in implementing LIKE in PDO
I have this query:
$query = "SELECT * FROM tbl WHERE address LIKE '%?%' OR address LIKE '%?%'";
$params = array($var1, $var2);
$stmt = $handle->prepare($query);
$stmt->execute($params);
I checked the $var1 and $var2 they contain both the words I want to search, my PDO is working fine since some of my queries SELECT INSERT they work, it's just that I am not familiar in LIKE here in PDO.
The result is none returned. Do my $query is syntactically correct?
You have to include the % signs in the $params, not in the query:
$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?";
$params = array("%$var1%", "%$var2%");
$stmt = $handle->prepare($query);
$stmt->execute($params);
If you'd look at the generated query in your previous code, you'd see something like SELECT * FROM tbl WHERE address LIKE '%"foo"%' OR address LIKE '%"bar"%', because the prepared statement is quoting your values inside of an already quoted string.
Simply use the following:
$query = "SELECT * FROM tbl WHERE address LIKE CONCAT('%', :var1, '%')
OR address LIKE CONCAT('%', :var2, '%')";
$ar_val = array(':var1'=>$var1, ':var2'=>$var2);
if($sqlprep->execute($ar_val)) { ... }
No, you don't need to quote prepare placeholders. Also, include the % marks inside of your variables.
LIKE ?
And in the variable: %string%
$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?";
$params = array("%$var1%", "%$var2%");
$stmt = $handle->prepare($query);
$stmt->execute($params);
You can see below example
$title = 'PHP%';
$author = 'Bobi%';
// query
$sql = "SELECT * FROM books WHERE title like ? AND author like ? ";
$q = $conn->prepare($sql);
$q->execute(array($title,$author));
Hope it will work.

How do I create a PDO parameterized query with a LIKE statement?

Here's my attempt at it:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE "?%"');
$query->execute(array('value'));
while ($results = $query->fetch())
{
echo $results['column'];
}
Figured it out right after I posted:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->execute(array('value%'));
while ($results = $query->fetch())
{
echo $results['column'];
}
For those using named parameters, here's how to use LIKE with % partial matching for MySQL databases: WHERE column_name LIKE CONCAT('%', :dangerousstring, '%')
where the named parameter is :dangerousstring.
In other words, use explicitly unescaped % signs in your own query that are separated and definitely not the user input.
Edit: Concatenation syntax for Oracle databases uses the concatenation operator: ||, so it'll simply become:
WHERE column_name LIKE '%' || :dangerousstring || '%'
However there are caveats as #bobince mentions here that:
The
difficulty
comes when you want to allow a literal % or _ character in the
search string, without having it act as a wildcard.
So that's something else to watch out for when combining like and parameterization.
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->bindValue(1, "%$value%", PDO::PARAM_STR);
$query->execute();
if (!$query->rowCount() == 0)
{
while ($results = $query->fetch())
{
echo $results['column'] . "<br />\n";
}
}
else
{
echo 'Nothing found';
}
You can also try this one. I face similar problem but got result after research.
$query = $pdo_connection->prepare('SELECT * FROM table WHERE column LIKE :search');
$stmt= $pdo_connection->prepare($query);
$stmt->execute(array(':search' => '%'.$search_term.'%'));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
This works:
search `table` where `column` like concat('%', :column, '%')
I got this from php delusions
$search = "%$search%";
$stmt = $pdo->prepare("SELECT * FROM table WHERE name LIKE ?");
$stmt->execute([$search]);
$data = $stmt->fetchAll();
And it works for me, very simple. Like he says , you have to "prepare our complete literal first" before sending it to the query
PDO escapes "%" (May lead to sql injection): The use of the previous code will give the desire results when looking to match partial strings BUT if a visitor types the character "%" you will still get results even if you don't have anything stored in the data base (it may lead sql injections)
I've tried a lot of variation all with the same result PDO is escaping "%" leading unwanted/unexcited search results.
I though it was worth sharing if anyone has found a word around it please share it
I had a similar need but was using a variable grabbed from a form. I did it like this to get results from my PostgreSQL DB, using PHP:
<?php
$player = $_POST['search']; //variable from my search form
$find = $sqlPDO->prepare("SELECT player FROM salaries WHERE player ILIKE ?;");
$find->execute(['%'.$player.'%']);
while ($row = $find->fetch()) {
echo $row['player']."</br>";
}
?>
The "ILIKE" makes the search non-case sensitive, so a search for cart or Cart or cARt will all return the same results.
The only way I could get this to work was to put the %$search% into another variable.
if(isset($_POST['submit-search'])){
$search = $_POST['search'];
}
$query = 'SELECT * FROM posts WHERE post_title LIKE :search';
$value ="%$search%";
$stmt= $pdo->prepare($query);
$stmt->execute(array(':search' => $value));
I don't know if this is the best way to do it, in the while loop I used:
while ($r = $stmt->fetch(PDO::FETCH_ASSOC)){

Categories