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

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)){

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)){

PHP variable in SQLite query

I'm a beginner with web-related coding and I'm trying to make a web-interface from where I can read and write to the sqlite database. My current problem is implementing a PHP-variable ($inNodeID) to sqlite query:
SELECT * FROM data WHERE NodeID = "$inNodeID"
If I replace the variable in query to the value of the variable ("ID007") everything seems to work. So what is wrong with my syntax in this manner?
$inNodeID = "ID007";
echo "Requested node: $inNodeID \n";
print "<table border=1>";
print "<tr><td>NodeID</td><td>MemoryIndex</td><td>DataIndex</td><td>TimeStamp</td></tr>";
$result = $db->query('SELECT * FROM data WHERE NodeID = "$inNodeID"');
//$result->bindParam(':inNodeID', $inNodeID, PDO::PARAM_STR);
foreach($result as $row)
{
print "<td>".$row['NodeID']."</td>";
print "<td>".$row['MemoryIndex']."</td>";
print "<td>".$row['DataIndex']."</td>";
print "<td>".$row['TimeStamp']."</td></tr>";
}
print "</table>";
It seems you were about to use the right way but for some reason gave up
Here you go:
$result = $db->prepare('SELECT * FROM data WHERE NodeID = ?');
$result->execute(array($inNodeID));
$data = $result->fetchAll();
foreach($data as $row)
...
With SQLite3, you can do it like this:
$query = $db->prepare('SELECT * FROM data WHERE NodeID = ? OR NodeID = ?');
$query->bindParam(1, $yourFirstNodeID, SQLITE3_INTEGER);
$query->bindParam(2, $yourSecondNodeID, SQLITE3_INTEGER);
$result = $query->execute();
var_dump($result->fetchArray());
You can find the documentation about bindParam here.
Problem is because of you have enclosed variable $inNodeID. If a variable is enclosed in Quotes PHP behave in different ways based on the Quote thats used. PHP evaluates a variable only when its enclosed in Double quotes, if its used with Single Quote then PHP treats it as a STRING.
please change your code to any one of the below option, your issue will be solved
Option 1
$result = $db->query("SELECT * FROM data WHERE NodeID = $inNodeID");
Option 2
$result = $db->query('SELECT * FROM data WHERE NodeID = '.$inNodeID);
For more info Check Out PHP Manual
you should do Three steps:
prepare your sql code with imaginary word and ":" instead of your variable like this:
$statement = $db -> prepare("SELECT * FROM table WHERE col_test = :imaginary_word");
bind your php variable with the previous step "imaginary word" like this:
$statement -> bindValue(':imaginary_word', $php_variable);
your statement which is a combination of your SQL code and PHP variables is ready and it's the time to execute it like this:
$your_result = $statement -> execute();
♦ now you can use this "$your_result" for fetch_array() , fetch_all Or anything you want...
You don't need to put " around the variable. So try:
$result = $db->query('SELECT * FROM data WHERE NodeID = ' . $inNodeID );

PHP "SHOW TABLES" MySQLi query not working

i'm trying to execute a prepared statement with php but it doesn't work. My prepared statement is like:
SHOW TABLES LIKE "italy_turin_mathematics"
and i do it like this:
if ($stmt = $this->mysqli->prepare("SHOW TABLES LIKE ?_?_?")) {
$stmt->bind_param('sss', "italy", "turin", "mathematics");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($column1);
while($stmt->fetch()) {
echo "Table: ".$column1;
}
}
I'm sure it must return something, because with PHPMyAdmin it does, but with PHP it always skips the while loop, i think there is something wrong with the prepared statement query, maybe it needs to escape the underscore char?
How can i do it?
Your database architecture is utterly wrong.
There should be only one table contains all the data, for all the places and sciences.
And you have to query it usual way, without employing SHOW TABLES at all.
So, it have to be something like
$sql = "SELECT * FROM t WHERE country=? AND city=? and science=?";
$stm = $pdo->prepare($sql);
$stm->execute(array("italy", "turin", "mathematics"));
$data = $stm->fetchAll();
the above code is in PDO, as you have to use it instead of mysqli.
Splitting tables is a very bad idea, violating the very fundamental rules of relational databases. As you can see, it makes you to run such a strange query and will make your further code even worse.
if ($stmt = $this->mysqli->prepare("SHOW TABLES LIKE ?")) {
$country = "italy";
$city = "turin";
$course = "mathematics";
$stmt->bind_param('s', $country . "_" . $city . "_" . $course);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($column1);
while($stmt->fetch()) {
echo "Table: ".$column1;
}
}
As far as I know the code you had would result in a query looking as follows:
SHOW TABLES LIKE 'italy'_'turin'_'mathematics'
You cannot concatenate like that in mySQL, or any form of SQL I can think of.
SHOW TABLES LIKE ?_?_?
Should be:
SHOW TABLES LIKE CONCAT(?, '_', ?, '_', ?) --this gives an error, see below
And I fully agree with #your-common-sense's commentary that this is a terrible way to design a database and you will come to regret it in more ways than just this one messed up query.
edit:
MySQL does not seem to allow functions in a SHOW TABLES statement, so either you'll have to concatenate the table name to a single string in PHP, or you can use a query like:
SELECT
TABLE_NAME
FROM
INFORMATION_SCHEMA.TABLES
WHERE
table_schema = 'mydb' AND
table_name LIKE CONCAT(?, '_', ?, '_', ?);

Categories