SQL LIKE not searching - php

I'm trying to find a value from my database using SQL LIKE:
SELECT id FROM titles WHERE skuid LIKE '%:cusa%'
Where :cusa is defined CUSA06536 as a dynamic value in my PHP code.
It should return:
But instead it returns nothing. No errors are outputted. Am I doing something wrong? Are dynamic values not supported?
PHP script:
public function findCusa($cusa) {
$find = $this->query("SELECT id FROM titles WHERE skuid LIKE '%:cusa%'");
$find->execute(array(":cusa" => $cusa));
if($find->rowCount() > 0) {
echo 'found!';
}
echo 'not found';
}
Then called as $ps->findCusa('CUSA06536'); which returns not found.

Don't add the % in the LIKE statement, instead do it in the PHP code. Most likely your DB framework is getting confused when you use a quoted bind parameter.
$find = $this->query("SELECT id FROM titles WHERE skuid LIKE :cusa");
$find->execute(array(":cusa" => '%' . $cusa . '%'));

try using a proper string eg: using concat
("SELECT id FROM titles WHERE skuid LIKE concat('%', :cusa, '%')");

Related

Codeigniter : how to write a query when the inside of the table have value ""

I've got a table in which a field contains pattern Like this [{"vendor":"10","status":"paid"}] :
table
I want to make a query 'like' in codeigniter , but I got an error:
model :
function get_total_order($id_vendor){
$this->db->like('payment_status', 'vendor":"'.$id_vendor.'","status":"due');
$this->db->from('sale');
return $this->db->count_all_results();
}
view :
<?php
$new_order = $this->crud_model->get_total_order($this->session->userdata('vendor_id'));
echo "<h1>".$new_order."</h1>";
?>
when i run this, i got blank page, how i fix this?
thanks.
Since you use "Like" query type, you should add '%' in the query argument or send a complete argument:
function get_total_order($id_vendor)
{
$this->db->like('payment_status', '%vendor":"'.$id_vendor.'","status":"due%');
$this->db->from('sale');
return $this->db->count_all_results();
}
Try this:
function get_total_order($id_vendor){
$this->db->like('vendor',$id_vendor);
$this->db->like('status',"due");
$this->db->from('sale');
return $this->db->count_all_results();
}
if your searching json data so you have pass the data in like query and like query data should be look like data inside the table how it looks .
your query should be something like this
<?php
$id_vendor =123;
$ss= '%"vendor":"'.$id_vendor.'","status":"due"%';
$sssss ="select * from sale where payment_status like '$ss' ";
echo $sssss;
query look like this
select * from sale where payment_status like '%"vendor":"123","status":"due"%'
?>
and also you can use wildcard (%) more place with your wish.
You can customize where as per your requirement with and condition or another condition.
$where = "payment_status like '%$id_vendor%' OR status like '%$status%'";
$this->db->where($where);
try this one:
Because 'like is time consuming.
function get_total_order($id,$vendor)
{
$this->db->where('vender', $id);
$this->db->where('status',$vendor);
$this->db->get('sale');
$result=$res->result_array();
return $result;
}
You can use $this->db->where_in() like below:-
$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')
For more details, please check below link:-
https://www.codeigniter.com/userguide2/database/active_record.html

How to run a LIKE %..% query using RedBean

I would like to run a query at Redbean.
The query is the following one
"SELECT * FROM tablename WHERE name LIKE "%querystring%" OR
description LIKE "%querystring%"
I tried the following one
$querystring = "querystring";
R::findOne( 'SELECT * FROM tablename WHERE name LIKE ? OR description
LIKE ?', "%$querystring%");
However, this did not work, resulting in error 'Identifier does not conform to RedBeanPHP security policies'.
Another thing I tried was based on this:
R::getAll( 'SELECT * FROM table WHERE title LIKE %:title%',
[':title' => 'home']
);
That gave a RedBean error 'undefined offset: 0'
I'm trying to find a way to do this using prepared statements, so I don't want to construct the query as a string and send it to the server later.
The syntax you need is following:
$mySearchString = "es";
$bean = R::find('bean',' name LIKE :name ',
array(':name' => '%' . $mySearchString . '%' )
);
So as you see the LIKE is written without the wildcards in the sql statement, because that is part of the searchValue. Your first try was quite there, yet the problem was that you've written the php variable inside the quotes thus it didn't resolve.
Also findOne/find are the ORM features of RedBean which are not working with pure SQL strings. Take a closer look on the docs. If you need pure sql try R:getAll like you did. Same example with that one here
$mySearchString = "es";
$bean = R::getAll('SELECT * FROM bean WHERE name LIKE :name ',
array(':name' => '%'.$mySearchString.'%' )
);
foreach($bean as $entry) {
echo $entry['name'] . "<br />";
}
try that
SELECT * FROM tablename WHERE name LIKE '%$querystring%'
OR description LIKE '%$querystring%'
may be you can use like:
"%".$querystring."%"

MySQL "LIKE" clause for filtering against strings

I'm trying to create a filter system for my site. The current code looks like this:
$DB->query("SELECT id FROM filter WHERE filter LIKE '%". $Properties['Title'] ."%'");
if($DB->record_count() != 0) {
$Err = '[b]Cannot upload this![/b]';
include(SERVER_ROOT . '/sections/upload/upload.php');
die();
}
*Note: $DB->record_count = function to cover mysqli_num_rows
Ofcause, we got $Properties to be the properties of uploaded element, and thereby Title to to be the string title
Example, an upload could be:
Me.And.My.Dog.At.The.Lake
and there is a record in the filter database saying:
me.and.my.dog
The objective of the code is to make an error and not allow the upload to proceed.
If I understand correctly you can do it with a query like this
SELECT COUNT(*) matches
FROM filter
WHERE 'Me.And.My.Dog.At.The.Lake' LIKE CONCAT('%', filter, '%')
Note:
reverse upload name and filter when doing comparison with LIKE
return just the number of rows in the resultset using COUNT() instead of returning a resultset that potentially can contain multiple rows (even if it's only ids) and then read the count on the client side.
Consider using prepared statements instead of interpolating query strings.
Here is SQLFiddle demo
use following statement to fetch row count
if($DB->fetch(PDO::FETCH_NUM) != 0) {
$Err = '[b]Cannot upload this![/b]';
include(SERVER_ROOT . '/sections/upload/upload.php');
die();
}

SQL query failing

I want the query initially to return all records where c_id>0 and then filter based on the subsequent criteria supplied through text boxes. However, I am not getting any records printed the first time the page is accessed. Here is the code:
$ctitle = mysql_real_escape_string($_POST['ctitle']);
$csubject = mysql_real_escape_string($_POST['csubject']);
$creference = mysql_real_escape_string($_POST['creference']);
$cobjecttype = mysql_real_escape_string($_POST['cobjecttype']);
$cmaterial = mysql_real_escape_string($_POST['cmaterial']);
$ctechnic = mysql_real_escape_string($_POST['ctechnic']);
$cartist = mysql_real_escape_string($_POST['cartist']);
$csource = mysql_real_escape_string($_POST['csource']);
$sql = "SELECT * FROM collections WHERE (
c_id>0 AND
`ctitle` LIKE '{$ctitle}' AND
`csubject` LIKE '{$csubject}' AND
`creference` LIKE '{$creference}' AND
`cobjecttype` LIKE '{$cobjecttype}' AND
`cmaterial` LIKE '{$cmaterial}' AND
`ctechnic` LIKE '{$ctechnic}' AND
`csource` LIKE '{$csource}' AND
`cartist` LIKE '{$cartist}'
)ORDER BY c_id DESC";
When I echo the query I get the following printed instead:
request "Could not execute SQL query" SELECT * FROM collections WHERE ( c_id>0 AND `ctitle` LIKE '' AND `csubject` LIKE '' AND `creference` LIKE '' AND `cobjecttype` LIKE '' AND `cmaterial` LIKE '' AND `ctechnic` LIKE '' AND `csource` LIKE '' AND `cartist` LIKE '' )ORDER BY c_id DESC
Where should I go from here?
Put a space between ) and ORDER BY
You don't need the braces around tow where clause elements.
Ok... I think I got it... Try replacing LIKE '' with LIKE '%'
LIKE '' will not work because it only shows empty columns. By adding a wildcard (%) it will show all rows matching everything. But it might be a better and cleaner solution to build your query completely dynamically, omitting empty WHERE conditions.

PHP mysql - ...AND column='anything'...?

Is there any way to check if a column is "anything"? The reason is that i have a searchfunction that get's an ID from the URL, and then it passes it through the sql algorithm and shows the result. But if that URL "function" (?) isn't filled in, it just searches for:
...AND column=''...
and that doesn't return any results at all. I've tried using a "%", but that doesn't do anything.
Any ideas?
Here's the query:
mysql_query("SELECT * FROM filer
WHERE real_name LIKE '%$searchString%'
AND public='1' AND ikon='$tab'
OR filinfo LIKE '%$searchString%'
AND public='1'
AND ikon='$tab'
ORDER BY rank DESC, kommentarer DESC");
The problem is "ikon=''"...
and ikon like '%' would check for the column containing "anything". Note that like can also be used for comparing to literal strings with no wildcards, so, if you change that portion of SQL to use like then you could pre-set the variable to '%' and be all set.
However, as someone else mentioned below, beware of SQL injection attacks. I always strongly suggest that people use mysqli and prepared queries instead of relying on mysql_real_escape_string().
You can dynamically create your query, e.g.:
$query = "SELECT * FROM table WHERE foo='bar'";
if(isset($_GET['id'])) {
$query .= " AND column='" . mysql_real_escape_string($_GET['id']) . "'";
}
Update: Updated code to be closer to the OP's question.
Try using this:
AND ('$tab' = '' OR ikon = '$tab')
If the empty string is given then the condition will always succeed.
Alternatively, from PHP you could build two different queries depending on whether $id is empty or not.
Run your query if search string is provided by wrapping it in if-else condition:
$id = (int) $_GET['id'];
if ($id)
{
// run query
}
else
{
// echo oops
}
There is noway to check if a column is "anything"
The way to include all values into query result is exclude this field from the query.
But you can always build a query dynamically.
Just a small example:
$w=array();
if (!empty($_GET['rooms'])) $w[]="rooms='".mysql_real_escape_string($_GET['rooms'])."'";
if (!empty($_GET['space'])) $w[]="space='".mysql_real_escape_string($_GET['space'])."'";
if (!empty($_GET['max_price'])) $w[]="price < '".mysql_real_escape_string($_GET['max_price'])."'";
if (count($w)) $where="WHERE ".implode(' AND ',$w); else $where='';
$query="select * from table $where";
For your query it's very easy:
$ikon="";
if ($id) $ikon = "AND ikon='$tab'";
mysql_query("SELECT * FROM filer
WHERE (real_name LIKE '%$searchString%'
OR filinfo LIKE '%$searchString%')
AND public='1'
$ikon
ORDER BY rank DESC, kommentarer DESC");
I hope you have all your strings already escaped
I take it that you are adding the values in from variables. The variable is coming and you need to do something with it - too late to hardcode a 'OR 1 = 1' section in there. You need to understand that LIKE isn't what it sounds like (partial matching only) - it does exact matches too. There is no need for 'field = anything' as:
{field LIKE '%'} will give you everything
{field LIKE 'specific_value'} will ONLY give you that value - it is not partial matching like it sounds like it would be.
Using 'specific_value%' or '%specific_value' will start doing partial matching. Therefore LIKE should do all you need for when you have a variable incoming that may be a '%' to get everything or a specific value that you want to match exactly. This is how search filtering behaviour would usually happen I expect.

Categories