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."%"
Related
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, '%')");
I am using PostgreSQL Database. create a search query in using codeigniter like function.
$this->db->($colName."::text", $value)->get("datatables_demo");
SELECT * FROM "datatables_demo" WHERE "first_name::text" like '%co%'
But in PostgreSQL shows error, I want output like that
SELECT * FROM "datatables_demo" WHERE first_name::text like '%co%'
Is there any option in codeigniter to remove inverted comma from like function
ihave tried to send false in 3rd argument false
$this->db->($colName."::text", $value, false)
Give any option to resolve this issue using like function
Query:SELECT * FROM "datatables_demo" WHERE "salary::text" LIKE
'%320%' ESCAPE '!'
When i run this query in postgresql
ERROR: column "salary::text" does not exist
LINE 1: SELECT * FROM "datatables_demo" WHERE "salary::text" LIKE ...
^
********** Error **********
ERROR: column "salary::text" does not exist
SQL state: 42703
Character: 40
But when i remove inverted comma from column it return result succuessfully
SELECT * FROM "datatables_demo" WHERE salary::text LIKE '%320%'
ESCAPE '!'
If you thinking of sql like function
try this.
$sql = ('SELECT * FROM datatables_demo WHERE salary::text LIKE ?');
$query = $this->db->query($sql, array($value . '%'));
I think in codeigniter2 PostgreSql driver has like operator previous versions codes.
If you want to in use codeigniter like function to build query you have to make some change in codeigniter system database library
I am give you changes in this path
system\database\drivers\postgre\postgre_driver.php
In line no 36
var $_escape_char = '"';
Replace with
var $_escape_char = '';
Your query output same as you expected o/p
BEST OF LUCK
I have made a simple amateur component in Joomla...
In it there is a select>option drop-down list, which add parameters to the URL.
The problem was that it did not worked with 1.1 value and it works with a 1.5 value.
A friend of mine fixed the problem, but I want to know why it happened
Original Query:
$query = "SELECT * FROM `TABLE 2` WHERE Power='".$_GET["Power"]."' AND Poles='".$_GET["Poles"]."'";
The new working query:
$query = "SELECT * FROM `TABLE 2` WHERE Power=".floatval($_GET["Power"])." AND Poles='".$_GET["Poles"]."'";
If you're using Joomla, you should really be sticking to Joomla's coding standards and methods for everything, this includes database queries:
https://docs.joomla.org/Selecting_data_using_JDatabase
You should also be using JInput instead of $_POST or $_GET calls:
http://docs.joomla.org/Retrieving_request_data_using_JInput
Looking at your query, it should looking something like this:
$db = JFactory::getDbo();
$input = JFactory::getApplication()->input;
$power = $input->get('Power', '', 'RAW');
$polls = $input->get('Pols', '', 'RAW');
$query = $db->getQuery(true);
$query->select($db->qn(array('*')))
->from($db->qn('#__table'))
->where($db->qn('Power') . ' = ' . $db->q($power), 'AND')
->where($db->qn('Polls') . ' = ' . $db->q($polls));
$db->setQuery($query);
$results = $db->loadObjectList();
// Do what you want with the $results object
Using this means that column names and data values are escaped properly and you've not left with SQL vulnerabilities as #skidr0w mentioned.
Note: #__ is the database table prefix, assuming you've followed this approach. If not, simply replace #__table with the full name of your table
The table column Power is of type float or double. In your first query you try to insert a string value. The second query inserts the correct float by first casting the request value to float and removing the quotes around the value.
By the way, you sould never ever use unfiltered user-input (such as $_GET values) in a sql query.
Actually, after several days I found that the problem and the solution were simpler.
Just removing the '-sign solved the problem
Power='".$_GET["Power"]."'
with
Power=".$_GET["Power"]."
Regards
The raw query I'm trying to get plugged in here is:
SELECT * FROM x WHERE CONCAT(y, ' ', x) LIKE '%value%';
I've checked through the AR docs and can't find anything that would allow me to do this. I'm not very familiar with how exactly it's constructing these queries, and was hoping someone could point me in the right direction. Thanks a bunch.
If you want to use the AR class you need to pass FALSE as third parameter to avoid the query being escaped automatically. You are now left to escaping the argument by yourself:
$value = $this->db->escape_like_str($unescaped);
$this->db->from('x');
$this->db->where("CONCAT(y, ' ', x) LIKE '%".$value."%'", NULL, FALSE);
$result = $this->db->get();
Refer to point 4) in the Active Record session of the manual. Quoting:
Custom string:
You can write your own clauses manually:
$where = "name='Joe' AND status='boss' OR status='active'";
$this->db->where($where);
$this->db->where() accepts an optional third parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks.
$this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);
An easier way, imho, whould be to run a "regular" query and take advantage of binding:
$result = $this->db->query("CONCAT(y, ' ', x) LIKE '%?%'", array($value));
Or use an associative array method without using the third parameter:
$a = array(
'CONCAT(`y`, " ", `x`)' => $value,
'title' => $title,
...
);
...
$this->db->like($a);
Will be generated WHERE part of the query:
... WHERE CONCAT(`y`, " ", `x`) LIKE '%test value%' AND `title` LIKE '%test title%' AND ...
Obviously useful when using more than one search parameters.
something like this should work:
$this->db->where("CONCAT(y, ' ', x) LIKE '%value%'");
$this->db->get(x);
This is old but...
You can try this:
$this->db->like('CONCAT(field_name," ",field_name_b)',$this->db->escape_like_str('value'));
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.