ORDER BY is not working with mysql multiple queries - php

I am using multiple queries and it's working fine, the only issue I am facing is that order by is not working. I tried some code like
$query = "SELECT id, name, reg_number, class, section FROM register where id IS NOT NULL ORDER BY `id` DESC";
it's working fine in phpmyadmin and giving me a proper result. But it's not working where I want to use it.
$query = "SELECT id, name, reg_number, class, section FROM register where id IS NOT NULL ";
if ( $name !="" ){
$query .= " AND `name` LIKE '".$name."%'"; // id is greater then
}
if ( $status !="" ){
$query .= " AND `status` LIKE '".$status."%'"; // id is greater then
}
if ( $id_from !="" ){
$query .= " AND id >= $id_from "; // id is greater then
}
if ( $id_to !="" ){
$query .= " AND id <= $id_to "; // id is shorter then
}
if ( $class !="" ){
$query .= " AND class IN($class)"; // Selecting class
}
if ( $section !="" ){
$query .= " AND section IN($section)"; // selecting section
}
$result = mysql_query($query);
I want to use order by in this query but order by is not working with this.
$query = "SELECT id, name, reg_number, class, section FROM register where id IS NOT NULL ORDER BY `id` DESC";
AND also used
$query = "SELECT id, name, reg_number, class, section FROM register where id IS NOT NULL ORDER BY id DESC";
I don't know what's the problem with my code.

Just add ORDER BY when finish your WHERE:
if ( $section !="" ){
$query .= " AND section IN($section)"; // selecting section
}
$query .= " ORDER BY id DESC";
$result = mysql_query($query);

Related

Trying to select from database and insert default value

I'm trying to figure how to select from database and add the default value when pressing a button. What I'm trying to say is when the button is pressed it would select the table it would insert default values?
function budget_item($from_date, $to_date, $account) {
$from = date2sql($from_date);
$to = date2sql($to_date);
$sql = "SELECT SUM(amount)
FROM ".TB_PREF."budget
WHERE account=".db_escape($account);
if ($from_date != "")
$sql .= " AND tran_date >= '$from' ";
if ($to_date != "")
$sql .= " AND tran_date <= '$to' ";
$result = db_query($sql,"No budget were returned");
$row = db_fetch_row($result);
return $row[0];
$sql = "INSERT INTO ".TB_PREF."budget(
account) VALUES ('$date',
".db_escape($account).",".db_escape($amount).")";
}

Search multiple values if present

sorry my English is weak ....
how can i search multi values from db SQL So that there was any.
i can search name && family together but
I want when the user searched name And family leave empty Return result correctly
how can i write this
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$sql = "select * from myinfo WHERE name='{$_POST['searchname']}' && family='{$_POST['searchfamily']}' ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}
Your 3 main issues here..
the first being WHERE name= now.. name is already used by mysql therefore you shouldn't use it however.. If you do use it run it like this:
WHERE `name`=
You should always backtick database tables and columns to make life easier in the long haul.
The second issue being you used && where it should be AND
the third is you shouldn't be placing your variables straight into your query as you're left open for SQL Injection.
Now I'm running on the assumption you're using $mysqli as your variable however, this may need adjusting to suit the correct variable you are using:
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$searchName = $_POST['searchname'];
$family = $_POST['searchfamily'];
$sql = $mysqli->prepare("select * from `myinfo` WHERE `name` = ? OR `family`= ? ORDER BY `id` DESC");
$sql->execute([$searchName, $family]);
} else {
$sql = $mysqli->prepare("select * from `myinfo` ORDER BY `id` DESC");
$sql->execute();
}
If you want to search with both then you need to change your if also. And change && to and in your query
if (isset($_POST['searchname']) && isset($_POST['searchfamily'])) {
$sql = "select * from myinfo WHERE `name`='{$_POST['searchname']}' AND family='{$_POST['searchfamily']}' ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}
Edit
As per your comment try this:
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$where="";
if(isset($_POST['searchname']))
$where=" WHERE `name`='{$_POST['searchname']}'";
if(isset($_POST['searchfamily']))
{
if($where=="")
$where=" WHERE family='{$_POST['searchfamily']}'";
else
$where=" AND family='{$_POST['searchfamily']}'";
}
$sql = "select * from myinfo $where ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}

Search Form Multi Input

I have a search form with 2 select fields and one input, total 3 options, so i created some if statements, depending of each fields are set it haves is own query, but its not working well, is all buggy, the results doesn't get right, it gets mixed up with the statements queries, it's not getting right.
Here is my code for the search form result:
$keywords = $_GET["Keywords"];
$location = $_GET['Location'];
$jobtype = $_GET["Category"];
if (isset($location) && empty($jobtype) && empty($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
country = '$location'
ORDER BY id_job DESC";
}elseif(isset($location) && isset($jobtype) && empty($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
country = '$location' AND
jobType_en = '$jobtype'
ORDER BY id_job DESC";
}elseif(isset($location) && isset($jobtype) && isset($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
country = '$location' AND
jobType_en = '$jobtype' AND
title_en LIKE '%$keywords%'
ORDER BY id_job DESC";
}elseif(empty($location) && isset($jobtype) && empty($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
jobType_en = '$jobtype'
ORDER BY id_job DESC";
}elseif(empty($location) && isset($jobtype) && isset($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
jobType_en = '$jobtype' AND
title_en LIKE '%$keywords%'
ORDER BY id_job DESC";
}elseif(empty($location) && isset($jobtype) && isset($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
jobType_en = '$jobtype' AND
title_en LIKE '%$keywords%'
ORDER BY id_job DESC";
}
else{
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1'
ORDER BY id_job DESC";
}
$consultaJob = mysql_query($sql_jobs);
You need to simplify the code:
$sql = "SELECT * FROM jobs
WHERE
active = '1' AND
country = '$location' ";
$order = "ORDER BY id_job DESC";
$where = "";
if( isset( $jobtype ) { $where .= " AND jobType_en = '$jobtype'"; }
if( isset($keywords) { $where .= " AND title_en LIKE '%$keywords%'" };
$sqlx = $sql . $where . $order;
You are obviously processing $jobtype and $keywords earlier on. In this processing you should be setting some default values to make later processing easier.
$jobtitle = (isset( $_GET['jobtitle'] ) ) ? $_GET['jobtitle'] : "";
$keywords= (isset( $_GET['keywords'] ) ) ? $_GET['keywords'] : "";
This way you can use:
if( $jobtitle != '') { .... }
You may want to try strlen() rather than isset or empty
otherwise you have to use both isset() and empty()
empty() does not generate a warning if the variable does not exist.
strlen() will return zero on NULL and ''.
You can set minimum lengths by changing the zero to a higher value.
elseif(strlen($location) > 0 && strlen($jobtype) > 0 && strlen($keywords) > 0 ){
If the submitted values are text inputs then you may need the trim also:
elseif(strlen(trim($location)) > 0 && strlen(trim($jobtype)) > 0 && strlen(trim($keywords)) > 0 ){

PHP Optimized query call if nothing is selected

I am trying to make my coding more efficient and I am stuck at how to tell the query to display all the categories if nothing is selected.
I have 15 categories that the user can chose from, if none is selected, display all items. Rather than doing AND .. AND .. AND 15 times if nothing is selected, is there a smarter way for this?
This will work for one category selection:
$cate = mysql_query("SELECT * FROM `posts` ORDER BY `id` ASC");
while($row = mysql_fetch_assoc($cate)){
if($user_data['category'] === $row['id']) {
echo '<li>'.$row['name'].'</li>';
}
}
$category_list = "AND `category_id` = '".$user_data['category']."'";
You should generate your query dynamically
// General query
$query = "SELECT * FROM `posts`";
// If category selected
if ($user_data['category'] != 0) {
$query .= " WHERE `category_id` = '".$user_data['category']."'";
}
// Order
$query .= " ORDER BY `id` ASC";
// Run query
$cate = mysql_query($query);
Or it can be simplified using Ternary Operator:
// Generate query
$query = "SELECT * FROM `posts` ".($user_data['category'] != 0 ? "WHERE `category_id` = '".$user_data['category']."'" : "" )." ORDER BY `id` ASC";
// Run query
$cate = mysql_query($query);

Cant figure out how to code this in php

I am trying to $_GET some variables that a user may enter (busy making a basic web-server):
$users= strval($_GET['user']);
$price= intval($_GET['price']);
$productID= intval($_GET['productid']);
This is my query:
$query = "SELECT * FROM `table` WHERE `user` = '" . $user . "' AND `price` <= " . $price . " AND `productID` = " . $productID;
(something like this)
Given this theoretical link:
www.example.com/api.php?price=300
And don't use the rest of the GET (user and productID) will automatically be filled with either 0 or '' (int/string).
So I thought I could use an if statement:
if(price == 0){
// change the query without the price as WHERE
}
But what if I have combinations of price and productID or productID and user as variables.
What is the best way to handle this? Maybe it's a stupid question but I can't figure it out.
You can use combined IF statements to build the appropriate query using the variables if they are supplied (and ignoring them if not)
$query = "SELECT * FROM `table` WHERE 1"; // WHERE 1 means "return all rows from table"
if ( isset( $_GET['price'] ) ){ // Only if price variable is set
$query .= " AND price <= '{$_GET['price']}'"; // Restrict results by price
}
if ( isset( $_GET['user'] ) ){ // Only if user variable is set
$query .= " AND user LIKE '{$_GET['user']}'"; // Restrict results by user
}
if ( isset( $_GET['productID'] ) ){ // Only if user variable is set
$query .= " AND productID = '{$_GET['productID']}'"; // Restrict results by productID
}
You can use ternary operator to make query string correctly, concatenating price clause when it is set.
$query = "select * from table where user = $user" . ($price ? " AND price <= $price" : "") . " AND productID = $productID";
Your english is poor, we are brazilians o/
$users = $_GET['user'] || "";
$price = $_GET['price'] || 0;
$productID = $_GET['productid'] || 0;
$query = "SELECT * FROM table WHERE 1";
$query .= (isset($_GET['user'))?"AND user = '{$users}'";
$query .= (isset($_GET['price'))?"AND price <= '{$price}'";
$query .= (isset($_GET['productid'))?"AND productID = '{$productID}'";
In case you want to use the variables for something else. This sets the values to 0 or "" (empty string) if they aren't set in the $_GET data.

Categories