PHP Search query result ORDER BY not working - php

I have this code to search database. It now works perfectly but i want to change the order of which it displays. Below is my code.
if (isset($_GET["mainSearch"]))
{
$condition = '';
$query = explode(" ", $_GET["mainSearch"]);
foreach ($query as $text)
{
$condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$order = "ORDER BY quiz_id DESC";
$sql_query = "SELECT * FROM questions WHERE " . $condition;
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition . $order;
$result = $db->query($sql_query);
$resultCount = $db->querySingle($sql_query_count);
if ($resultCount > 0)
{
if ($result)
{
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
echo '<div class="quesbox_3">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$row["answer"].'</div>
</div>';
}
}
}
else
{
echo "No results found";
}
}
I want the ORDER of which result show to be from bottom to top. Please how can i add this properly as current code isn't working.

Your putting the order by on the count() query, which doesn't do much really.
$sql_query = "SELECT * FROM questions WHERE " . $condition;
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition . $order;
Try
$sql_query = "SELECT * FROM questions WHERE " . $condition. ' '. $order;
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition ;

Your $order is in your count query alone. Add to your $sql_query
$sql_query = "SELECT * FROM questions WHERE " . $condition . ' '. $order;

Give 1 space in this string
$order = " ORDER BY quiz_id DESC ";
It is not showing you because if you echo your query than it will show like this
SELECT COUNT(*) as count FROM questions WHERE question LIKE '%test%'ORDER BY quiz_id DESC
You can see in this echo query there is a no space between ORDER and %test%
do Like this it will helps you.

Query Space issues. can you try with this query
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition .' '. $order;

Related

PHP filters combining into one SQL query

I'm trying to filter through my database according to filters done by visitors.
$query = "select * from Sheet1 where";
//filter query start
if (!empty($brand)) {
$branddata = implode("','", $brand);
//testing removing query
$query .= " Brand in('$branddata') and";
}
if (!empty($model)) {
$modeldata = implode("','", $model);
//testing removing query
$query .= " Model in('$modeldata') and";
}
/* if(!empty($model) && empty($brand)){
} */
if (!empty($spower) && !empty($epower)) {
$query .= " Power>='$spower' and Power<='$epower' and";
}
if (!empty($sprice) && !empty($eprice)) {
$query .= " Doors>='$sprice' and Doors<='$eprice'";
}
$rs = mysqli_query($conn, $query) or die("Error : " . mysqli_error($conn));
The result I wish to get is a sql query that works and has correct syntax. Such as select * from Sheet1 where Doors>='$sprice' and Doors<='$eprice', if the visitor is filtering by price.
Currently, my code is made so that it simply adds a certain string to the variable. This means that if you don't filter by model, it skips model, because the model variable is empty. The problem comes to if you filter by power, the SQL will become select * from Sheet1 where Power>='$spower' and Power<='$epower' and. Obviously this doesn't work, so I need help in making the code make sure it works for every combination of filters.
Append $query .= " 1 = 1"; at the end. I did some modification in your given code. Have a look.
<?php
$query = "SELECT * FROM `Sheet1` WHERE";
//filter query start
if(!empty($brand)){
$branddata = implode("','",$brand);
$query .= " (Brand in('$branddata')) AND";
}
if(!empty($model)){
$modeldata = implode("','",$model);
$query .= " (Model in('$modeldata')) AND";
}
if(!empty($spower) && !empty($epower)){
$query .= " (Power>='$spower' AND Power<='$epower') AND";
}
if(!empty($sprice) && !empty($eprice)){
$query .= " (Doors>='$sprice' AND Doors<='$eprice') AND"; //Added 'AND'
}
$query .= " 1 = 1"; //Added new line
$rs = mysqli_query($conn,$query) or die("Error : ".mysqli_error($conn));
?>
Add AND on each query appended in if conditions. Then, at last add $query .= " 1 = 1";. Which will save you from extra AND coming at the end. If none of the conditions satisfy, then your query will be SELECT * FROM Sheet1 WHERE 1 = 1. Simple. And, don't forget to differentiate between conditions in query. Differentiate your conditions like how I did by opening and closing brackets.
I would do it this way
$filters=array();
if(!empty($brand)){
$branddata =implode("','",$brand);
//testing removing query
$filters[]= " Brand in('$branddata')";
}
if(!empty($model)){
$modeldata =implode("','",$model);
//testing removing query
$filters[]= " Model in('$modeldata') and";
}
if(!empty($spower) && !empty($epower)){
$filters[]= " Power>='$spower' and Power<='$epower' and";
}
if(!empty($sprice) && !empty($eprice)){
$filters[]= " Doors>='$sprice' and Doors<='$eprice'";
}
$query = "select * from Sheet1 where";
foreach ($filters as $filter) {
$query.=' AND '.$filter;
}
$rs = mysqli_query($conn,$query) or die("Error : ".mysqli_error($conn));

Search query array value binding not working

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 :)

PHP & Mysql Not ordered correctly

I have latest MySQL version (5.5) and this is the screenshot of groupid field
I didn't touch anything yet, but some cells are not ordered correctly like this
But if I click groupid name in the top, it will ordered correctly like this:
Below PHP code output is like first screenshot above, that are not ordered correctly. Please help how to make the output ordered correctly, like it is displayed in the second screenshot above,
Maybe add code like this : order by id asc, but which is the right place to add it below?
$group_ids = explode(" ", $options['groupchoice_ids']);
$groupsql = "SELECT id, title FROM " . TABLE_PREFIX . "thegroup WHERE";
$first = true;
foreach($group_ids as $value)
{
if (!$first)
{
$groupsql = $groupsql . " OR ";
}
else
{
$first = false;
}
$groupsql = $groupsql . " id = '" . $value . "' ";
}
$kh_optionsgroup = '<select name = "accounttype">';
$checksec = $db->query_read($groupsql);
if ($db->num_rows($checksec))
{
while ($lboard = $db->fetch_array($checksec))
{
$kh_optionsgroup = $kh_optionsgroup . "<option value
='" . $lboard['id'] . "'>" . $lboard['title'] . "</option>";
}
}
$verifystring = '$human_verify';
$kh_optionsgroup = $kh_optionsgroup . "</select>";
At the end of your query, you need to set an order, like so:
$groupsql="SELECT id, title FROM " . TABLE_PREFIX . "thegroup WHERE";
$first=true;
foreach($group_ids as $value){
if(!$first){
$groupsql = $groupsql." OR ";
}else{
$first = false;
}
$groupsql = $groupsql." id = '".$value."' ORDER BY groupid ASC";
}
ORDER BY id ASC
This will make the query return its results in ascending order from the groupid column. Simply change ASC to DESC if you want it to go descendinng (high->low).

Query Structure: SELECT FROM places WHERE Type = 1

Okay so i am trying to display all entries in one of my database tables where the field 'Type' has a value of 1 but i keep getting an error. I'm not sure how to structure my query.
<?php
include 'page-start.php';
?>
<?php
$myQuery = "SELECT places.*, Type.TypeName ";
$myQuery .= "FROM places ";
$myQuery .= "WHERE Type = '1' ";
$myQuery .= "INNER JOIN Type ON places.Type = Type.TypeID";
$result = $con->query($myQuery);
if (!$result) die('Query error: ' . mysqli_error($result));
?>
<?php
while($row = mysqli_fetch_array($result))
{
echo ' <div class="one-third column" id="education">';
echo '<h3 class="place-head">' . $row['PlaceName'] . '</h3>';
echo ' <div class="a-image">';
echo '<img src="'. $row['ImageURL'] . '"/>';
echo ' </div>';
echo ' <div class="a-info">';
echo ' </div>';
echo '</div>';
}
?>
After playing around i managed to get it working by executing the query on its own underneath the first query like this:
<?php
$myQuery = "SELECT places.*, Type.TypeName ";
$myQuery .= "FROM places ";
$myQuery .= "INNER JOIN Type ON places.TypeID = Type.TypeID";
$result = $con->query($myQuery);
if (!$result) die('Query error: ' . mysqli_error($result));
?>
<?php
$myQuery = "SELECT * FROM `places` WHERE `TypeID` = '1'";
$result = $con->query($myQuery);
if (!$result) die('Query error: ' . mysqli_error($result));
?>
I don't know if this was the correct way of getting round my problem but it works. Thanks for the help anyway guys.
I believe you have an SQL syntax error?
$myQuery = "SELECT places.*, Type.TypeName ";
$myQuery .= "FROM places ";
$myQuery .= "WHERE Type = '1' ";
$myQuery .= "INNER JOIN Type ON places.Type = Type.TypeID";
The inner join should precede your predicate ("WHERE Type = '1'"):
$myQuery = "SELECT places.*, Type.TypeName ";
$myQuery .= "FROM places ";
$myQuery .= "INNER JOIN Type ON places.Type = Type.TypeID";
$myQuery .= "WHERE Type = '1' ";
Don't pass $result to mysqli_error, that's not what it wants, it wants your $con variable passed in as the parameter.
Also, since you're using the mysqli object, just call $con->error to print the error message.
And since you're returning a mysqli_result objects, you should probably just use
while ($row = $result->fetch_array(MYSQLI_ASSOC) )
as your while loop command.

PHP/mySQL Like function does not work

I have a simple query in PHP but I can't get Like to work.
Here is the code:
$var = $_GET['q'];
$trimmed = trim($var);
$query = "SELECT * FROM vm_regiony WHERE nazev LIKE "%$trimmed%" order by id LIMIT 10";
$result = mysql_query($query);
if(mysql_num_rows($result)==0){
echo "nothing";
echo "<br />";
echo $trimmed;
}else{
while($rene=mysql_fetch_array($result)){
$jmeno = $rene['nazev'];
echo '<a id="hled" onclick="javascript:vybrat()">'.$jmeno.'</a>';
For one you need to use single quotes there
$query = "SELECT * FROM vm_regiony WHERE nazev LIKE '%$trimmed%' order by id LIMIT 10";
$query = "SELECT * FROM vm_regiony
WHERE nazev LIKE '%' . $trimmed . '%'
ORDER BY id LIMIT 10";

Categories