SQL query failing - php

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.

Related

SQL LIKE not searching

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, '%')");

where clause not working with like query

I have a search query and when I search all like keywords work properly the records are showing with the matched criteria, but the problem is that where clause in not working.
$position = $this->session->set_userdata('position', $this->input->post('position'));
$adress_all = explode(",", $this->session->userdata('address'));
$this->db->like('address', $adress_all[0]);
$this->db->or_like('game', $this->session->userdata('skills'));
$this->db->or_like('gender', $this->session->userdata('coach'));
$this->db->or_like('Positions', $this->session->userdata('position'));
$this->db->where('type', 'private');//all other type coaches is also showing up
$sql = $this->db->get('coach');
You need to use Grouping LIKE of codeigniter
$this->db->group_start();
$this->db->like('address', $adress_all[0]);
$this->db->or_like('game', $this->session->userdata('skills'));
$this->db->or_like('gender', $this->session->userdata('coach'));
$this->db->or_like('Positions', $this->session->userdata('position'));
$this->db->group_end();
$this->db->where('type', 'private');
$sql = $this->db->get('coach');
Hope this works(need to test on your DB)
See Doc
Try below things.
$this->db->where('type', 'private');//all other type coaches is also showing up
$this->db->where("(address LIKE '%". $adress_all[0]."%' OR game LIKE '%".$this->session->userdata('skills')."%' OR gender LIKE '%".$this->session->userdata('coach')."%' OR positions LIKE '%".$this->session->userdata('position')."%')",null,false);
$sql = $this->db->get('coach');

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."%"

Get PHP to read my postgres select statement?

I have an application that was built by someone else that I need to edit. There is an area of code that I cannot find the right syntax for ... can someone please help.
The select statement in POSTGRES goes like this:
SELECT collection|| '/' ||color AS collection
FROM table
WHERE series = 'random number' <-- this is controlled by an array in the php
in the php the existing code looks like this:
$tableName = $db->getOne('SELECT collection FROM item_series WHERE series = ?', array($series['marriage_1']));
}else{$tableName = $series['marriage_1'];}
I have tried this, but it is not working:
$tableName = $db->getOne('SELECT collection, ".'/'.", color AS collection FROM item_series WHERE series = ?', array($series['marriage_1']));
}else{
$tableName = $series['marriage_1'];}
Please help I have looked for an answer to this for hours!
Wouldn't it be this?
$db->getOne('select collection || \'/\' || color as collection ...', ...);
Or this?
$db->getOne("select collection || '/' || color as collection ...", ...);
Your attempt:
'SELECT collection, ".'/'.", color AS collection FROM item_series WHERE series = ?'
would end this SQL to the database:
SELECT collection, "/", color AS collection FROM item_series ...
and PostgreSQL wouldn't be upset with you for trying to use double quotes for a string literal, it would think you were trying to access a column called /. Besides, you want to concatenate and you want to use the || SQL operator for that.

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