I tried to make a search system which uses the LIKE operator to search results based on what the user typed. I'm using it with strings. The problem is that it doesn't show any result.
I hope this also helps people with the same confusion as me...
Code:
"SELECT * FROM table WHERE name LIKE ' . $input . ';";
input is a PHP variable from what the user typed.
EDIT: Don't worry about SQL injection, it's all offline.
for the proper use of like you should use wildchar eg :
SELECT * FROM table WHERE name LIKE concat('%', ? ,'%') ;
and you should not use var inside SQL code .. you are at risk for sqlinjectiomn
for avoid this you should take a look at you db driver for prepared statement and binding param
eg for PDO
$st = $conn->prepare("SELECT * FROM table WHERE name LIKE concat('%', ? ,'%')");
$st->bindParam(1, $input, PDO::PARAM_STR, 255);
$st->execute();
Try This
$string = "input";
$sql = "select * from table where name like '%$string%'"
Create a variable and store value what you want to search
$where = "AND name like '%$string%'";
and put it after table name
$sql = "select * from table_name $where";
Related
I have multiple tables in my database named teacher1, teacher2.... I am trying to access them using a variable $id.
I have written down the following code.
$query = "SELECT * FROM table.$id";
How could i access those different tables using a variable.
I'm not clear from the question text whether your $id variable contains the full table name, or some kind of number.
However, in either case you have to make a slight tweak to your $query variable.
If $id contains the full name of the table (i.e. teacher1):
$query = "SELECT * FROM " . $id;
If $id contains a number used to identify which teacher table it is (i.e. 1, 2, 3, etc):
$query = "SELECT * FROM teacher" . $id;
Learn to use parameters!
$stmt = $conn->prepare($query = "SELECT t.* FROM table t where t.id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
Don't munge query strings with parameter values! This introduces SQL injection risk, can introduce syntax errors that are hard to debug, and can degrade performance.
The last time I have posted a question about searching JSON data using PHP. After testing the script I wanted to try something else. Using MySQL to search through the data. Since it is faster than looping everything using a PHP script.
I was writing the script in PhpMyAdmin and that has generated the next PHP script for me. But somewhere there is a bug (sad)
"SELECT *
FROM `bigtree_pages`
WHERE `resources` like \'%\"XNCatDesc\": \"%?%\' and `resources` like \'%\"Brand\": \"%?%\' and `resources` like \'%\"ItemDesc\": \"%?%\'"
I want to give three values. The Categorie, the brand, and the ItemDesc (the name). But this throws an error.
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near '\'%"XNCatDesc": "%'41'%\' and resources like \'%"Brand":
"%'none'%\' and `reso'
To be honest, I don't really know where I have to put my % sign.
For example. I have this in my JSON "Brand": "Bullet",
The value needs to be Brand (since we are searching on the Brand) and the brand is Bullet. What is the best way to write this query?
To use a parameter inside a LIKE expression in a prepared query, you need to form the entire expression and use that as the parameter. Otherwise you run into issues as you have with the insertion of quotes into your value. If you are using mysqli, try something like this (assuming your connection is called $conn and the values you want to search for are called $categorie, $brand and $itemdesc):
$stmt = $conn->prepare("SELECT *
FROM `bigtree_pages`
WHERE `resources` like ? and `resources` like ? and `resources` like ?");
$search_categorie = "%\"XNCatDesc\": \"%$categorie%\"";
$search_brand = "%\"Brand\": \"%$brand%\"";
$search_itemdesc = "%\"ItemDesc\": \"%$itemdesc%\"";
$stmt->bind_param("sss", $search_categorie, $search_brand, $search_itemdesc);
$stmt->execute();
However the problem you will run into is that because of the % surrounding the search values (e.g. $brand) in the query, when searching for brand = X you could match for example
"Brand": "Y", "Other Value": "contains an X"
So instead you should use regular expressions e.g.
$stmt = $conn->prepare("SELECT *
FROM `bigtree_pages`
WHERE `resources` rlike ? AND `resources` rlike ? AND `resources` rlike ?");
$search_categorie = '"XNCatDesc":[[:space:]]+"[^"]*' . $categorie;
$search_brand = '"Brand":[[:space:]]+"[^"]*' . $brand;
$search_itemdesc = '"ItemDesc":[[:space:]]+"[^"]*' . $itemdesc;
$stmt->bind_param("sss", $search_categorie, $search_brand, $search_itemdesc);
$stmt->execute();
If you are running MySQL 5.7 or later, this is better done using the inbuilt JSON_EXTRACT function:
$stmt = $conn->prepare("SELECT *
FROM `bigtree_pages`
WHERE JSON_EXTRACT(`resources`, '$.XNCatDesc') LIKE ? and
JSON_EXTRACT(`resources`, '$.Brand') LIKE ? and
JSON_EXTRACT(`resources`, '$.ItemDesc') LIKE ?");
$search_categorie = "%$categorie%";
$search_brand = "%$brand%";
$search_itemdesc = "%$itemdesc%";
$stmt->bind_param("sss", $search_categorie, $search_brand, $search_itemdesc);
$stmt->execute();
Currently I have a query that searchs for sentences/words, it works almost as expected,
I have a regex expresion that searches for names in a table, expample:
function getNames($str){
$stmt = "SELECT * FROM users WHERE name = :name
OR name REGEXP :reg1
OR name REGEXP :reg2
OR name LIKE :lik1";
$query = self::$connection->prepare($stmt);
$query->execute(array(":name"=>$str,
":reg1"=>"^$str" . "[a-zA-Z\s]*$",
":reg2"=>"^[a-zA-Z]*[\s]*[$str][a-zA-Z]"
":lik1"=>"%" . $str . "%"
));
return $query->fetchAll(PDO::FETCH_ASSOC);
}
Let's suppose my table contains the following values
Bob
Peter
Mark
David
John
If I run my query with Bob as $name value it gets it but I would like to be able to find Bob when I run the query using BobsomeLettersExtra or Bob something as $name value
Is there a way to do this using REGEXP or LIKE ?
SELECT * FROM users WHERE name LIKE '%".$name."%'
above query should be enough to get the result. You should validate data before you enter data to the table if not please use the regex as well
"SELECT * FROM users WHERE name LIKE '%".$name."%' AND REGEXP ^".$name."[a-zA-Z]*$"
UPDATE
sorry if i have misunderstand the question please try this
"Select * from users WHERE '".$name."' LIKE CONCAT(name , '%')"
You may try below Query with where Clause for LIKE :
"SELECT * FROM users WHERE name = ".$name." OR name LIKE '%".$name."%' OR name REGEXP ^".$name."[a-zA-Z]*$"
currently I've been using this:
SELECT * FROM `meow` WHERE profile LIKE '%$username%'
But the problem I'm facing is if someone puts the letters 'a' it will pull everything that contains a and that's a bit of a security risk on my end, How do i search just 1 column to see if it matches $username exactly? not the whole table?
For exact string matching you should the = operator instead of the like operator:
SELECT * FROM `meow` WHERE profile = '$username'
Stop using string concatenation to build your query. It's evil. Instead use mysqli or pdo and use prepared statements.
$pdo = new PDO('mysql:host=localhost;dbname=yourdb', 'your_username', 'your_password');
$stmt = $pdo->prepare("SELECT * FROM `meow` WHERE profile = ?");
$stmt->execute(array($username));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Also, use equality, instead of like, if you wish to check for exact matches.
Instead of using like use equal to
try this :
SELECT * FROM meow WHERE profile = '$username'
Try with -
"SELECT * FROM `meow` WHERE profile LIKE '$username'"
for exact match.
I'm building a script where users can search a database. my understanding is that PDO doesn't let you set a parameter for the LIKE operand. So I have this code to make up for it
$sQuery = "SELECT * FROM table WHERE column LIKE '%" . $this->sQuery . "%' LIMIT 30";
$Statement = $this->Database->prepare($sQuery);
$Statement->execute();
I doubt this is secure against SQL injection. Is there any way to make it secure?
You're right, interpolating any value into an SQL string creates a risk for SQL injection vulnerability. It's better to use a SQL query parameter placeholder when you prepare(), and then supply the value as a parameter when you execute().
$pattern = "%" . $this->sQuery . "%";
$sQuery = "SELECT * FROM table WHERE column LIKE ? LIMIT 30";
$Statement = $this->Database->prepare($sQuery);
$Statement->execute(array($pattern));
Take that as pseudocode because I can't tell from your example which MySQL extension you're using. I'm assuming PDO, which allows parameters to be sent as an array argument to execute().
Some people use PDOStatement::bindParam(), but there's no advantage to doing so. Maybe in some other RDBMS brands the PDO::PARAM_STR matters, but in the MySQL driver, the parameter type is ignored.
PS: Aside from the security issue you asked about, you will find a search for wildcard-based patterns like you're doing don't perform well as your data grows larger. See my presentation Full Text Search Throwdown.
This should work:
$sQuery = "SELECT * FROM table WHERE column LIKE :query LIMIT 30";
$Statement = $this->Database->prepare($sQuery);
$Statement->execute(array(':query' => '%' . $this->sQuery . '%'));