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.
Related
Given SQL-query with placeholders:
SELECT * FROM table WHERE `a`=? AND `b`=?
and query parameters ['aaa', 'bbb'], i would like to replace ?-placeholders with corresponding params. So, I do it like this:
$sql = preg_replace(array_fill(0, count($params), '#\?#'), $params, $sql, 1);
(we do not concentrate on mysql-escaping, quoting etc. in this question).
Everything works fine and I get
SELECT * FROM table WHERE `a`=aaa AND `b`=bbb
But if our first parameter looks like this: "?aa", everything fails:
SELECT * FROM table WHERE `a`=bbba AND `b`=?
obviously, first replacement pass changes "a=?" into "a=?aa", and second pass changes this (just inserted) question mark into "bbb".
The question is: how can I bypass this confusing preg_replace behaviour?
You can use preg_replace_callback to use one item from $params at a time for each replacement.
$sql = 'SELECT * FROM table WHERE `a`=? AND `b`=?';
var_dump('Original: ' . $sql);
$params=['aaa','bbb'];
$sql = preg_replace_callback("/\\?/",function($m) use (&$params) {
return array_shift($params);
}, $sql);
var_dump('Result: ' . $sql);
Let me know
I would not do this with preg_replace or str_replace. I would use preg_split so empty returns can be removed (If explode had empty removal option I'd use that). For there iterate over the return and add in values. You also can quote the values with this. I presume the purpose of this is for debugging parameterized queries.
$sql = 'SELECT * FROM table WHERE `a`=? AND `b`=?';
$v = array('1?1', "222");
$e = preg_split('/\?/', $sql, NULL, PREG_SPLIT_NO_EMPTY);
$c = '';
foreach($e as $k => $v1){
$c .= $v1 . "'" . $v[$k] ."'";
}
error_log($c);
Then your error log will have:
SELECT * FROM table WHERE `a`='1?1' AND `b`='222'
SO i get data from a form using this
$LoadId=implode(',',array_filter($_POST["load"]));
I then would like to submit this to a MSSQL query with an "in" statement
where myLoadId in $LoadId
but the $LoadID looks like 7209,7210 and I need it to look like
('7209','7210')
Seems your LoadId column contains interger value so why you need single quotes ' around it? Simply use-
$LoadId=implode(',',array_filter($_POST["load"]));
$query = "SELECT * FROM your_table WHERE myLoadId IN ($LoadId)";
echo $query;
If you still need quotes around it then you can do it this way-
$LoadId = "'".implode("','", array_filter($_POST["load"]))."'";
$query = "SELECT * FROM your_table WHERE myLoadId IN ($LoadId)";
echo $query;
WORKING DEMO: https://3v4l.org/2XEjJ
Put simple quotes around the implode() and change it's glue from , to ',' :
$LoadId = "'".implode("','", array_filter($_POST["load"]))."'";
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";
My goal is to search column A for string B and if it is found, return which row it was found in, and if it wasn't found, I would need to know that as well in order to take a different course of action.
My current PHP code:
$string = "teststring";
$searchquery = "SELECT *
FROM AllStringsTable
WHERE `Column_A` LIKE '$string'"
$searchresult = mysql_query($searchquery) or die(mysql_error());
$row = mysql_fetch_row($searchresult);
echo "The returned row was: $row";
This just breaks and does nothing, so I think I'm way off here. Also, I have read that for exact string searching that doesn't require wildcard substrings, etc, LIKE is not needed. So I'm not sure what I would use instead...
You're almost there. You need the % wildcards:
// First, prevent sql injection with mysql_real_escape_string
$string = mysql_real_escape_string($string);
$searchquery = "SELECT * FROM AllStringsTable WHERE `Column_A` LIKE '%{$string}%'";
// ----------------------------------------------------------------^^^-------^^^
$searchresult = mysql_query($searchquery) or die(mysql_error());
if (mysql_num_rows($searchresult) == 0) {
echo "no rows found";
}
else {
// You need to loop over the result resource to get all the rows.
// Better to use mysql_fetch_array()
while ($row = mysql_fetch_array($searchresult)) {
$print_r $row;
}
If you want to do an exact match, use = instead of LIKE:
SELECT ... WHERE Column_A = '$string';
If you want to do a substring match (which I suspect is more what you want), use LIKE with the % wildcards:
SELECT ... WHERE Column_A = '%$string%';
The difference is that the first query requires that the entire Column_A matches exactly. The second query requires only that the exact word is found somewhere in the column.
Basically i want to add wildcards to the the col value when searching...
Usually I do this the other way around like this:
WHERE cakes.cake_name LIKE '%$cake_search%'
however now i want it to match the inverse:
the user searches for 'treacle
sponge', i want this to match a row
where the cake_name column =
'sponge'.
is this possible?
WHERE '$cake_search' LIKE concat('%',cakes.cake_name, '%')
should work. It will need a full table scan but so will the inverse query. Have you looked into full text search for MySQL? It will likely make this sort of query more efficient.
Why not using MATCH?
MATCH(`cake_name`) AGAINST ('treacle sponge')
You would have to split the user supplied input on the space character and dynamically construct your query to check the column for those values:
$input = "treacle sponge";
$input_words = explode(' ', $input);
$sql_where = "WHERE cakes.cake_name IN('" . implode("','", $input_words) . "')"; // generates: WHERE cakes.cake_name IN('treacle','sponge')
In order to prevent SQL-Injection, I suggest using prepared statements.
$prepStmt = $conn->prepare('SELECT ... WHERE cakes.cake_name LIKE :cake_search
');
if($prepStmt->execute(array('cake_search'=>"%$cake_search%"))) {
...
}
Or, using full text search:
$prepStmt = $conn->prepare('SELECT ... WHERE MATCH (`cake_name`) AGAINST (:cake_search IN BOOLEAN MODE)');
if($prepStmt->execute(array('cake_search'=>$cake_search_words))) {
...
}
See JSON specialchars JSON php 5.2.13 for a complete example.. ;)