I'm working on a search query and i hit a little bump... So as you see in the code below, i'm adding values to a array to execute it later in the script, but it's not really working... So when i var_dumped all of this, it returned like it is supposed to but the :q was not changed to the value which was entered in the link.
$query = "SELECT * FROM articles";
$columnsQuery = [];
$values = [];
if(isset($_GET['q']) && !empty($_GET['q']))
{
$columnsQuery[] = " WHERE MATCH (title) AGAINST (':q' IN NATURAL LANGUAGE MODE)";
$values[":q"] = $_GET['q'];
}
$fullQuery = $query . implode(" ", $columnsQuery)
. " ORDER BY id DESC"
. " LIMIT {$paginator->getLimitSQL()}";
$getArticles = $db->prepare($fullQuery)->execute($values);
$query = "SELECT * FROM articles";
$columnsQuery = [];
$values = [];
if(isset($_GET['q']) && !empty($_GET['q']))
{
$columnsQuery[] = " WHERE MATCH (title) AGAINST (':q' IN NATURAL LANGUAGE MODE)";
$values["q"] = $_GET['q']; // TRY WITHOUT COLON
}
$fullQuery = $query . implode(" ", $columnsQuery)
. " ORDER BY id DESC"
. " LIMIT {$paginator->getLimitSQL()}";
$getArticles = $db->prepare($fullQuery)->execute($values);
You should not use colon in the place of $values["q"] = $_GET['q'];
$query = "SELECT * FROM articles";
$columnsQuery = [];
$values = [];
if(isset($_GET['q']) && !empty($_GET['q']))
{
$columnsQuery[] = " WHERE MATCH (title) AGAINST (':q' IN NATURAL LANGUAGE MODE)";
$values["q"] = $_GET['q']; // TRY WITHOUT COLON
}
$fullQuery = $query . implode(" ", $columnsQuery)
. " ORDER BY id DESC"
. " LIMIT {$paginator->getLimitSQL()}";
$getArticles = $db->prepare($fullQuery)->execute($values);
$query = "SELECT * FROM articles";
$values = array();
if(!empty($_GET['q'])) {
$query .= " WHERE MATCH (title) AGAINST (q IN NATURAL LANGUAGE MODE)";
$db->bindParam(':q', $_GET['q']);
}
$fullQuery = $query . " ORDER BY id DESC" . " LIMIT {$paginator->getLimitSQL()}"
$getArticles = $db->prepare($fullQuery)->execute();
So after a while i figured it out, You're not supposed to use parameters while binding in the query, and like #Poiz pointed out i shouldnt use colons in the array either
Thx to everyone who tried helping :)
Related
I have a database filled with addresses. 6 columns (id, Name, Address, City, State, Zip, dt)
My code is run with ajax for live search. Currently I can mostly find what I'm looking for with my queries. The problem I'm running into is this. If I search for "90210 Steve Jones" I get no results but if I search for "Steve Jones 90210" it finds the row(s).
Here is my code:
$query = "SELECT * FROM db";
if($_POST['query'] != '')
{
$postq = mysql_real_escape_string($_POST['query']);
$query .= "WHERE CONCAT(Name,Address,City,State,Zip) LIKE '%".str_replace(' ', '%', $postq)."%'";
}
$query .= 'ORDER BY Name ASC, dt DESC ';
$statement = $connect->prepare($query);
$statement->execute();
Any help would be appreciated
One of the solutions is to split the search string by spaces and then do a multiple like comparison operations
So the code is:
<?php
if($_POST['query'] != '') {
$postq = mysql_real_escape_string($_POST['query']);
$pieces = explode(" ", $postq);
$index=0;
$substring="";
while ($index < count($pieces)) {
$substring .=" CONCAT(Name,Address,City,State,Zip) like '%" . $pieces[$index] . "%'" ;
if ($index !=count($pieces)-1){
$substring .= " and ";
}
$index++;
}
$query = "SELECT * FROM db where ";
$query .= $substring;
$query .= ' ORDER BY Name ASC, dt DESC ';
$statement = $connect->prepare($query);
$statement->execute();
}
?>
You could break up your query by spaces and test for each.
$query = "SELECT * FROM db";
$where = [];
$values = [];
$ss = [];
if($_POST['query'] != '')
{
foreach( explode(' ', $_POST['query']) as $p) {
$postq = mysql_real_escape_string($p);
$where[]= "(CONCAT(Name,Address,City,State,Zip) LIKE ? )";
$values[] = "%$postq%";
$ss[]='s';
}
$query .= " WHERE " . implode(" OR ", $where);
}
$query .= ' ORDER BY Name ASC, dt DESC ';
$statement = $connect->prepare($query);
if(count($values)>0) $statement->bind_param(implode('',$ss), ...$values);
$statement->execute();
I use str_replace and does not work properly.
I have a QueryString I want to replace some of the words with the amount of input, but the str_replace method does not work and does not change anything.
$inputdata = json_decode(file_get_contents('php://input'), true);
$query2 = $inputdata["QueryString"] . $where . " ORDER BY " .$inputdata["DataRequest"]["Sort"][0]["field"]." " .$inputdata["DataRequest"]["Sort"][0]["dir"]. " LIMIT ".$inputdata["DataRequest"][take]." OFFSET " .$inputdata["DataRequest"][offset];
for ($x = 0; $x < count($parameters); $x++) {
$query2 = str_replace($inputdata["parameters"][$x][key],$inputdata["parameters"][$x][value],$query2);
}
query2return :
" SELECT Members.*, HouseholdAdmin.AdminCode FROM Members JOIN HouseholdAdmin ON Members.HouseholdAdminId=HouseholdAdmin.HouseholdAdminId WHERE MemberId =%MemberId "
str_replace($inputdata["parameters"][$x][key],$inputdata["parameters"][$x][value],$query2); not work
$query2 = str_replace('%MemberId','2',$query2); not work.
$query2 = str_replace('SELECT','dsdfsdfsdf',$query2); not work.
$query2 = str_replace('anyThing','anyThing',$query2); not work.
,....
It does not matter which words I enter & replace in str_replace, nothing works.
$query2 = str_replace($inputdata["parameters"][$x][key],$inputdata["parameters"][$x][key],$query2);
$query2 = str_replace('%MemberId','2',$query2);
$query2 = str_replace('SELECT','dsdfsdfsdf',$query2);
$query2 = str_replace('anyThing','anyThing',$query2);
This query is not returning any result as there seems to be an issue with the sql.
$sql = "select region_description from $DB_Table where region_id='".$region_id."' and region_status =(1)";
$res = mysql_query($sql,$con) or die(mysql_error());
$result = "( ";
$row = mysql_fetch_array($res);
$result .= "\"" . $row["region_description"] . "\"";
while($row = mysql_fetch_array($res))
{
echo "<br /> In!";
$result .= " , \"" . $row["region_description"] . "\"";
}
$result .= " )";
mysql_close($con);
if ($result)
{
return $result;
}
else
{
return 0;
}
region_id is passed as 1.
I do have a record in the DB that fits the query criteria but no rows are returned when executed. I beleive the issue is in this part ,
region_id='".$region_id."'
so on using the gettype function in my php it turns out that the datatype of region_id is string not int and thus the failure of the query to function as my datatype in my tableis int. what would be the way to get parameter passed to be considered as an int in php. url below
GetRegions.php?region_id=1
Thanks
Try it like this:
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"
The region_id column seems to be an integer type, don't compare it by using single quotes.
Try dropping the ; at the end of your query.
First of all - your code is very messy. You mix variables inside string with escaping string, integers should be passed without '. Try with:
$sql = 'SELECT region_description FROM ' . $DB_Table . ' WHERE region_id = ' . $region_id . ' AND region_status = 1';
Also ; should be removed.
try this
$sql = "select region_description from $DB_Table where region_id=$region_id AND region_status = 1";
When you are comparing the field of type integer, you should not use single quote
Good Luck
Update 1
Use this.. It will work
$sql = "select region_description from " .$DB_Table. " where region_id=" .$region_id. " AND region_status = 1";
You do not need the single quotes around the region id i.e.
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"
I have a search engine type website. It takes the users input, stores the query as $q, explodes the query and searches the database. It then displays the results with the name and web address of each result.
For example, if i searched for "computer programming"... Stack Overflow, stackoverflow.com would be my result. However, it displays twice. (once for computer, and once for programming.)
I tried to solve this with the array_unique function, and it does not work.
any help would be appreciated.
// trim whitespace
$trimmed = trim($q);
// seperate key-phrases
$trimmed_array = explode(" ", $trimmed);
// remove duplicates
$clean_array = array_unique($trimmed_array);
//query dataabase
foreach ($clean_array as $trimm){
$query = mysql_query("SELECT * FROM forumlist WHERE `keys` LIKE '%" . mysql_real_escape_string($trimm) . "%' ORDER BY rating DESC, total_ratings DESC") or die(mysql_error());
Thank you!
//query dataabase
$query = 'SELECT * FROM forumlist ';
$where = array();
foreach ($clean_array as $trimm){
$where[] = " `keys` LIKE '%" . mysql_real_escape_string($trimm) . "%' ";
}
if(!empty($where)){
$query .= " WHERE ". implode(' OR ', $where);
}
$query .= " ORDER BY rating DESC, total_ratings DESC";
$result = mysql_query($query) or die(mysql_error());
if i have 4 variables and i want to select DISTINCT values form data base
<?php
$var1 = ""; //this variable can be blank
$var2 = ""; //this variable can be blank
$var3 = ""; //this variable can be blank
$var4 = ""; //this variable can be blank
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE **keywords ='$var1' OR author='$var2' OR date='$var3' OR forums='$var4'** ");
?>
note: some or all variables ($var1,$var2,$var3,$var4) can be empty
what i want:
i want to neglect empty fields
lets say that $var1 (keywords) is empty it will select all empty fileds, but i want if $var1 is empty the result will be like
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE author='$var2' OR date='$var3' OR forums='$var4' ");
if $var2 is empty the result will be like
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE keywords ='$var1' OR date='$var3' OR forums='$var4' ");
if $var1 and $var2 are empty the result will be like
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE date='$var3' OR forums='$var4' ");
and so on
Try this.
$vars = array(
'keywords' => '', // instead of var1
'author' => '', // instead of var2
'date' => '', // instead of var3
'forums' => '', // instead of var4
);
$where = array();
foreach ($vars as $varname => $varvalue) {
if (trim($varvalue) != '') $where[] = "`$varname` = '" . mysql_real_escape_string($varvalue) . "'";
}
$result = mysql_query("SELECT DISTINCT title, description FROM table WHERE " . join(" OR ", $where));
Thanks alot every one specially experimentX .. Your answer helped me to get the right function i Just replaced (isset) with (!empty) .. Then every thing will be more than OK
$vars = array(
(!empty($_GET["var1"]))? " keyword = '". $_GET["var1"] ."' ": null,
(!empty($_GET["var2"]))? " author = '". $_GET["var2"] ."' ": null,
(!empty($_GET["var3"]))? " date = '". $_GET["var3"] ."' ": null,
(!empty($_GET["var4"]))? " forums = '". $_GET["var4"] ."' ": null
);
function myfilterarray($var)
{
return !empty($var)?$var: null;
}
$newvars = array_filter($vars, 'myfilterarray');
$where = join(" OR ", $newvars);
$sql = "SELECT DISTINCT title, description FROM table ".(($where)?"WHERE ".$where: null);
echo $sql;
with this function if there is empty variable it will be neglected
Thanks again every one for your helpful suggestion
make your select statement string before you call mysql_query(...) so do something along the lines of this:
$queryString = "Select DISTINCT title, description FROM table WHERE";
if(!empty($var1))
$queryString .= " keywords = $var1";
and so forth for all of your variables. you could also implement a for loop and loop through your $var1 - $var# and check for !empty($var#)
Why do you not simply build a if else structure?
Like
if ($var1!="" && $var2!="" && $var3!="" && $var4!=""){
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE keywords ='$var1' OR author='$var2' OR date='$var3' OR forums='$var4' ")
} else if ($var2!="" && $var3!="" && $var4!=""){
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE author='$var2' OR date='$var3' OR forums='$var4' ");
} else if {
...
}
(I just posted the below in his duplicate post, so I'm re-posting the below here)
Forgive me if anything is wrong, it's very late here and I just typed this in notepad on Windows, without an environment to test on. * Use with caution * :)
$vars = array(
'blah1' => '',
'blah2' => '',
'blah3' => '',
);
$sql_statement = "SELECT first, last FROM names WHERE";
$clause = "";
foreach($vars as $k=$v)
{
$k = trim($k);
if(!empty($k))
{
$clause .= " `$k` = '$v' OR";
}
}
$clause = rtrim($clause, "OR");
// $clause should have what you want.
Well, there are manu ways of doing this but the shortest way I have found is creating an array of the following form
$vars = array(
(isset($_GET["var1"]))? " keyword = '". $_GET["var1"] ."' ": null,
(isset($_GET["var2"]))? " author = '". $_GET["var2"] ."' ": null,
(isset($_GET["var3"]))? " date = '". $_GET["var3"] ."' ": null,
(isset($_GET["var4"]))? " forums = '". $_GET["var4"] ."' ": null
);
function myfilterarray($var)
{
return !empty($var)?$var: null;
}
$newvars = array_filter($vars, 'myfilterarray');
$where = join(" OR ", $newvars);
$sql = "SELECT DISTINCT title, description FROM table ".(($where)?"WHERE ".$where: null);
echo $sql;
Your result for http://localhost/?var1=sadfsadf&var2=sadfasdf&var3=asdfasdf
SELECT DISTINCT title, description FROM table WHERE keyword =
'sadfsadf' OR author = 'sadfasdf' OR date = 'asdfasdf'
Your result for http://localhost/?
SELECT DISTINCT title, description FROM table