MySQL/PHP Concatenating condition operator (<= , >=) with string in WHERE clause - php

This is my first post,so i will do my best to be clear.
Here is my question :
suppose you have a var that contain an operator :
For example, $var = "<=";
And you are tempted to do this :
$query = "SELECT * FROM table WHERE".$attr." ".$var." ".$value;
(where $value is an integer),
Am i allowed to do this ?
If yes,
i have tried the same thing in my PHP script but it doesn't work ! (except for $var = "=") although it did work in phpmyadmin.
(My code is little bit long, but if you want i can post it).
I really appreciate any help.

You don`t have any space between WHERE and $attr, you will perhaps get your wanted effect by doing this:
$query = "SELECT * FROM table WHERE ".$attr." ".$var." ".$value;
Or just
$query = "SELECT * FROM table WHERE $attr $var $value";
Try to echo $query to the browser, and copy&paste that into phpmyadmin.

Related

Dynamic MySQL query

I'm trying to create a dynamic sql query that compares my cat column to whatever the user entered in a form. The idea is that I will be able to take a dynamic array of values and then compare them to the cat column. This is what I tried to do:
// Loop to get the array of values from form
$get_arr = $_GET;
foreach ($get_arr as $get) {
$var = "AND cat LIKE $get";
}
// SQL query
$sql = "SELECT * FROM items
WHERE title LIKE 'this'
AND description LIKE 'that'
'%$var%'";
It doesn't work -- $var always show up blank. What would the solution be?
You have several problems.
You're not escaping the input, so you're subject to SQL injection or syntax errors.
You need to put quotes around the LIKE parameter.
You're overwriting $var each time through the loop instead of appending to it.
You're not putting any spaces around the expression.
You're putting % around the whole $var, it should be inside the LIKE parameter.
foreach ($get_arr as $get) {
$get = mysqli_real_escape_string($conn, $get);
$var .= " AND cat like '%$get%'";
}
$sql = "SELECT * FROM items
WHERE title LIKE '%this%'
AND description LIKE '%that%'
%var";

Split mysql query and delete a part of that

I have many conditions in PHP function which every of them produces a mysql query.All conditions work correctly except one query which ends with AND operator.Before returning the query result I need to check if query ends with AND it should remove AND and then returnes the query.
This is the sample of query:
$query="select * from case where case_name='name' AND case_status='102' AND";
If this kind of query is produced I need to do:
1-If it ends with AND
2-remove AND
3-return the query without last AND
The result should be like this:
$query="select * from case where case_name='name' AND case_status='102' ";
I do not have much experience to work with PHP functions.How can I do this?
Thnaks for your help.
Try this,
$query="select * from case where case_name='name' AND case_status='102' AND"
$query = trim($query,'AND');
quick fix:
$query = preg_replace( "/AND$/", "", $query);
You should fix the logic of condition though.
like
$cond[] = "....";
$cond[] = "...."
....
then
$query = $query_first_half + implode ( " AND " , $cond );
Ultimately please use sql library like PDO
http://fi1.php.net/manual/en/class.pdo.php
explode the string and pop the last element .
$arr = explode(" ", $query);
$last = array_pop($arr);
if($last != "and")
{
array_push($arr,$last);
}
$query = implode(" ",$arr);
Run the $query them it should work
First your table name CASE is mysql reserved keyword you should rename your table to something else or escpae it by backticks `
you could use query without AND , and when you add other query just start by AND .
like that :
$query="select * from `case` where case_name='name' AND case_status='102'";
$query .= " AND .........";
so like that , your condition is not true then just first query will work , if condition is true then second query will work and it start by AND. You dont need to remove the AND.

php multiple word search algorithm/script doesn't work with single quotes around search array variable. what am i doing wrong?

i've got a basic search code to search through database when people search for more than 1 word. i've done loads of research and all the algortihms seem to be prety much the same. trim the search words. explode them into an array. then use either foreach or while to add each word of array onto the msql_query.
but there is a problem. here is my code:
if (isset($_POST['search'])){
$words = $_POST['searchfield'];
$arraySearch = explode(" ", trim($words));
$countSearch = count($arraySearch);
$a = 0;
$query = "SELECT * FROM parts WHERE ";
while ($a < $countSearch)
{
$query = $query."description RLIKE '$arraySearch[$a]'";
$a++;
if ($a < $countSearch)
{
$query = $query." AND ";
}
}
$results=mysql_query($query) or die($query);
if(!$results){
$msg = "No results, please try another search";}
}
ok so look at the second $query variable where it says "decription RLIKE '$arraySearch'"
For the search to work whatever word is in $arraySearch HAS to be in single quotes. BUT when i try it the script will just not run.
BUT if i take away the single quotes the script runs. but it doesn't perform the search. it dies and comes up with error. in this case i've made the error message the actual query to try and find out what's going wrong.
so if i take away the single quotes and search for "car tyre". the query will be SELECT * FROM parts WHERE description RLIKE car AND description RLIKE tyre but it won't work unless its like this: SELECT * FROM parts WHERE description RLIKE 'car' AND description RLIKE 'tyre'.
i know this because i have tested the earch by just typing it into another query to test it.
i've spent hours and hours trying to figure a way round this but i can't figure it out. why is it doing this to me? how do i get round it? and why doesn't anyone else seem to be having the same problem?????
thanx for help :)
.... added as afterthough:
i'm thinking that the only possible way of doing this is to have the single quotes already inside the variable. but i don't know how to do that. as in:
$arraySearch = ("'car'", "'tyre'"); any ideas?
To get the quotes to work correctly, try to write it like this:
$query = $query."description RLIKE '".$arraySearch[$a]."'";
Adding the ". and ." inside of the single quotes may solve your problem.
Try doing this:
$quote = "'";
$query = $query."description RLIKE $quote$arraySearch[$a]$quote";

PHP: strval in WHERE clause

Currently I have a piece of code that functions fine as it is. But what I really want to do is take the <?php if strval ..?> part and place it into the "SELECT * FROM projects" part as a WHERE clause. I am not sure whether this is possible or how to go about it. Any thoughts would be really valued. Hope this makes sense.
<?php
// ** User ID
$userid = $row_listelements ['id'];
// ** Projects
mysql_select_db($database_db, $db);
$query_activeusers = "SELECT * FROM projects ";
$activeusers = mysql_query($query_activeusers, $db) or die(mysql_error());
$row_activeusers = mysql_fetch_assoc($activeusers);
$totalRows_activeusers = mysql_num_rows($activeusers);
?>
<? do {?>
<?php if (!(strpos($row_activeusers['assignedto'], strval(",".$userid.",")) === false)) { ?>
<div><?=$row_activeusers['jobnumberdisplay'];?></div>
<?php } ?>
<? } while ($row_activeusers = mysql_fetch_assoc($activeusers)); ?>
<strong><?php echo $totalRows_activeusers; ?></strong>
In case your userid is a unique number, and I understand your question correctly, you could reach this by:
using IN - can handle strings and numbers (they have to be unique to make this work):
$query_activeusers = "SELECT * FROM projects WHERE ".$userid." IN (assignedto)";
or using FIND_IN_SET - can handle Strings and numbers is case sensitive:
$query_activeusers = "SELECT * FROM projects WHERE FIND_IN_SET('".$userid."', assignedto)"
But I think you should look at your database design. The trouble with including Foreign Keys in a delimited list like this is that whole point of a foreign key is to enable you to locate the information in the other table quickly, using Indexes. By implementing a database as it sounds you have, you have all sorts of issues to resolve.
i m not sure but maybe this will help you.
if(strval ...)
{
$where = "where field = $value";
}
Now you can use this $where variable in your select query. it will execute only if your if condition is satisfy.
If I understand your code correctly, you should use SQL LIKE, i.e. something like:
$query_activeusers = "SELECT * FROM projects WHERE assignedto LIKE '%," .
((int) $userid) . ",%'";
The cast to (int) here is done to ensure you have no special SQL characters in $userid - kind of cheap SQL quoting for values that are integers. You do not really need to use strval as concatenation into the string will convert that number into a string.

MySQL where clause equals anything (SELECT * WHERE col = ANY_VALUE)

I'd like to create a query in MySQL that has an optional value. When the value is specified the query is filtered by that value, when the value is not all rows are returned. Here's the idea:
public function doQuery($item = 'ANY_VALUE') {
$query = "SELECT * FROM table WHERE item = ?";
db->fetchAll($query,array($item))
...
}
doQuery(); // Returns everything
doQuery($item='item1'); // Returns only rows where item = 'item1'
Is there an easy way to do this without creating two query strings depending on the value of $item?
As far as I know, no such "any" placeholder exists.
If you can use LIKE, you could do
SELECT * FROM table WHERE item LIKE '%'
if you can append a condition, you could nullify the item clause like this:
SELECT * FROM table WHERE item = ? OR 1=1
(won't work in your example though, because you are passing "item" as a parameter)
That's all the options I can see - it's probably easiest to work with two queries, removing the WHERE clause altogether in the second one.
This would probably work, but I*m not sure whether it's a good idea from a database point of view.
public function doQuery($item = 'ANY_VALUE') {
$query = "SELECT * FROM table WHERE item = ? OR 1 = ?";
db->fetchAll($query,array($item, ($item == 'ANY_VALUE' ? 1 : 0))
...
}
Better way to do this is first generate sql query from the parameter you need to bother on, and then execute.
function doQuery($params) {
$query = 'SELECT * FROM mytable ';
if (is_array($params) // or whatever your condition ) {
$query .= 'WHERE item = ' . $params[0];
}
$query .= ' ;';
// execute generated query
execute($query);
}
You cannot get distinct results without giving distinct query strings.
Using $q = "... WHERE item = '$item'" you DO create distinct query strings depending on the value of $item, so it is not that different from using
$q = "..." . ($item=='ANY_VALUE' ? something : s_th_else);.
That said I see two or three options:
use function doQuery($item = "%") { $query = "SELECT ... WHERE item LIKE '$item'"; ...}
But then callers to that function must know that they must escape a '%' or '_' character properly if they want to search for an item having this character literally (e.g. for item = "5% alcoholic solution", giving this as argument would also find "50-50 sunflower and olive oil non alcoholic solution".
use function doQuery($item = NULL) { $query = "SELECT ..."; if ($item !== NULL) $query .= " WHERE item = '$item' "; ...} (where I use NULL to allow any other string or numerical value as a valid "non-empty" argument; in case you also want to allow to search for NULL (without quotes) you must choose another "impossible" default value, e.g., [], and you must anyway use a distinct query without the single quotes which however are very important in the general case), or even:
use function doQuery($item = NULL) { if($item === NULL) $query = "SELECT ..."; else $query = "SELECT ... WHERE item = '$item' "; ...}, which is more to type but probably faster since it will avoid an additional string manipulation (concatenation of the first and second part).
I think the 2nd & 3rd options are better than the first one. You should explain why you want to avoid these better solutions.
PS: always take care of not forgetting the quotes in the SQL, and even to properly escape any special characters (quotes, ...) in arguments which can depend on user input, as to avoid SQL injections. You may be keen on finding shortest possible solutions (as I am), but neglecting such aspects is a no-no: it's not a valid solution, so it's not the shortest solution!

Categories