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
Related
I am trying to fetch the no of records, but I am unable to write this query in yii. My sql query is given below.
select count(review) from review_business where (date_created>=DATE_FORMAT(NOW() ,'%Y-11-01')) and (date_created<=DATE_FORMAT(NOW() ,'%Y-12-01')) . I am currently writing this query in yii is given below.
$results=Yii::app()->db->createCommand()
->Select('count(review)')
->from('review_business')
->where('date_created'>=DATE_FORMAT(NOW() ,'%Y-11-01'))
->queryAll();
But I am getting this error Fatal error: Call to undefined function NOW() in G:\www\ba.dev\protected\views\business\stats.php on line 19. I am sure it is because of my poor yii query. Kindly correct my query.
If you are willing to run the entire query and not use the active record pattern You can try built-in YII commands to do that.
$query = 'select * from post where category=:category';
$list= Yii::app()->db->createCommand($query)->bindValue('category',$category)->queryAll();
Explanation: $query should be obvious and =:category is binding the variable category dynamically to the query for security reasons. In next line I am creating the query and substituting the value of category variable by using bindValue() function, finally queryAll retrieves all the records in the database. Hope it is clear now.
In your case
$query = "select count(review) as result from review_business where (date_created>=DATE_FORMAT(NOW() ,'%Y-11-01')) and (date_created<=DATE_FORMAT(NOW() ,'%Y-12-01'))" ;
$list= Yii::app()->db->createCommand($query)->queryAll();
Now you can access the result like this:
foreach ($rows as $row) {
$result = $row["result"];
}
Try this,
$results=Yii::app()->db->createCommand()
->Select('count(review)')
->from('review_business')
->where('date_created >=DATE_FORMAT(NOW() ,"%Y-11-01")')
->queryScalar();
Unless I am missing something very obvious, I would expect the values of $data1 and $data2 to be the same?? But for some reason when I run this scenario twice (its run once each function call so I'm calling the function twice) it produces different results.
Call 1: PDO = Blank, Sprintf = 3 rows returned
Call 2: PDO = 1 row, Sprintf = 4 rows (which includes the PDO row)
Can someone tell me what I'm missing or why on earth these might return different results?
$sql = "SELECT smacc.account as Smid,sappr.*,CONCAT('$domain/',filepath,new_filename) as Image
FROM `{$dp}table`.`territories` pt
JOIN `{$dp}table`.`approvals` sappr ON pt.approvalID = sappr.ID
JOIN `{$dp}table`.`sm_accounts` smacc ON pt.ID = smacc.posted_territory_id
LEFT JOIN `{$dp}table`.`uploaded_images` upimg ON pt.imageID = upimg.ID
WHERE postID = %s AND countryID = %s AND smacc.account IN (%s) AND languageID = %s";
echo sprintf($sql,$postID,$countryID,implode(',',$accs),$langID);
$qry1 = $db->prepare(str_replace('%s','?',$sql));
$qry1->execute(array($postID,$countryID,implode(',',$accs),$langID));
$data1 = $qry1->fetchAll();
print'<pre><h1>PDO</h1>';print_r($data1);print'</pre>';
$qry2 = $db->query(sprintf($sql,$postID,$countryID,implode(',',$accs),$langID));
$data2 = $qry2->fetchAll();
print'<pre><h1>Sprintf</h1>';print_r($data2);print'</pre><hr />';
The root of the problem is the implode(',',$accs) function.
While you are using sprintf() it will generate a coma separated list and that list will be injected into the query string.
The result will be something like this:
smacc.account IN (1,2,3,4,5)
When you are binding the same list with PDO, it handles it as one value (a string: '1,2,3,4,5'). The "result" will be something like this:
smacc.account IN ('1,2,3,4,5')
Note the apostrophes! -> The queries are not identical.
In short, when you are using PDO and binding parameters, you have to bind each value individually (you can not pass lists as a string).
You can generate the query based on the input array like this:
$query = ... 'IN (?' . str_repeat(', ?', count($accs)-1) . ')' ...
// or
$query = ... 'IN (' . substr(str_repeat('?,', count($accs)), 0, -1) . ')'
This will add a bindable parameter position for each input value in the array. Now you can bind the parameters individually.
$params = array_merge(array($postID, $countryID), $accs, array($langID));
$qry1->execute($params);
Yes as Kris has mentioned the issue with this is the IN part of the query. Example 5 on the following link helps fix this: http://php.net/manual/en/pdostatement.execute.php. I tried using bindParam() but that didn't seem to work so will use Example 5 instead.
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."%"
I am doing a ajax suggestion function
The user gives an input of a word (like ICE), then the ajax script passes this to a .php script and that script looks it up in the database and should suggest the word ICECREAM.
This is where I am stuck. I need a query which goes like this:
SELECT * FROM table WHERE first str_len($string) characters = $string
Could you help me out please?
You want LIKE for this.
SELECT
...
WHERE
field LIKE '$string%'
SELECT * FROM table WHERE first LIKE 'string%'
$length = strlen($input);
$statement = $pdoObject->prepare("SELECT * FROM table WHERE LEFT(first, $length) = :input");
$statement->execute(array(':input' => $input));
This is safe because $length is guaranteed to be an integer so no need to make it a parameter.
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.