Where do I insert the ORDER BY in my MYSQL query - php

I need to have my results sorted by "ORDER BY prod_name" in my SQL statement but I cannot figure out get it to work. I tried after
$thisProduct .= " AND prod_type = 1 ORDER BY prod_name";
and also after
$thisProduct .= " AND ID = '" . mysql_real_escape_string($_GET['product']) . "' ORDER BY prod_name";
But I cannot get my results to sort correctly. Am I placing the order by in the wrong spot or did I query the DB incorrectly?
Thank you in Advance, I am still pretty new at MYSQL queries.
$thisProduct = "SELECT prod_name AS Name, days_span, CONCAT(LEFT(prodID,2),ID) AS ID, geo_targeting FROM products WHERE status = 'Active' AND vendID = ".$resort['vendID'];
if (isset($_GET['product']) AND is_numeric($_GET['product'])) {
$thisProduct .= " AND ID = '" . mysql_real_escape_string($_GET['product']) . "'";
}
else {
$thisProduct .= " AND prod_type = 1";
}
$thisProduct .= " LIMIT 1";
$getThisProduct = mysql_query($thisProduct);
if (!$getThisProduct/* OR mysql_num_rows($getThisProduct) == 0 */) {
header("HTTP/1.0 404 Not Found");
require APP_PATH . '/404.html';
die();
}
$thisProductData = mysql_fetch_assoc($getThisProduct);

You should have:
$thisProduct .= " ORDER BY prod_name";
$thisProduct .= " LIMIT 1";
(Note that the LIMIT 1 means you only get one record).

Assuming that your query is correct and you want the first product by name:
$thisProduct .= " ORDER BY prod_name LIMIT 1";

I believe it should go right before your "LIMIT 1", as in:
$thisProduct .= " ORDER BY prod_name LIMIT 1";

Insert it before the LIMIT
$thisProduct .= " ORDER BY prod_name LIMIT 1";
You can the select syntax at http://dev.mysql.com/doc/refman/5.0/en/select.html

SELECT query usually takes following form
SELECT which_all_to_select
FROM which_table/tables
WHERE criteria
ORDER BY column_name ASC/DESC;
ASC ascending order, and DESC is descending order
This orders query results by column_name specified in ORDER BY clause .

Related

CodeIgniter get table count rows

I am new in CodeIgniter, I want to count all rows from database table but i use limit in query and i want all count without use limit how can i do ?
my code is below :
$sql = " SELECT intGlCode,fkCategoryGlCode,'C' as acctyp,varEmail,varContactNo as phone,CONCAT(varFirstName,' ',varLastName) as name,dtCreateDate,chrStatus,varMessage as message
FROM " . DB_PREFIX . "Customer WHERE varEmail='$userEmail'
UNION
SELECT intGlCode,'' as fkCategoryGlCode,'P' as acctyp,varEmail,varPhoneNo as phone,varName as name,dtCreateDate,chrStatus,txtDescription as message FROM
" . DB_PREFIX . "Power WHERE varEmail='$userEmail' ORDER BY intGlCode DESC
LIMIT $start, $per_page ";
$query = $this->db->query($sql)
i use limit for pagination but i want to get all record from table.
You can add new column in both above and below UNION queries. It will be like below.
select (select count(*) from your_query), your_columns from query_above_union
UNION
select (select count(*) from your_query), your_columns from query_below_union
your_query = your full actual query your are using currently.
Although I am not sure about Codeigniter. But sure about SQl.
* If you count all records with all data including limit, than you can use this code. please check it. I hope it will works for you.*
$countsql = " SELECT intGlCode,fkCategoryGlCode,'C' as acctyp,varEmail,varContactNo as phone,CONCAT(varFirstName,' ',varLastName) as name,dtCreateDate,chrStatus,varMessage as message
FROM " . DB_PREFIX . "Customer WHERE varEmail='$userEmail'
UNION
SELECT intGlCode,'' as fkCategoryGlCode,'P' as acctyp,varEmail,varPhoneNo as phone,varName as name,dtCreateDate,chrStatus,txtDescription as message FROM
" . DB_PREFIX . "Power WHERE varEmail='$userEmail' ORDER BY intGlCode DESC";
$sql = $countsql. " LIMIT $start, $per_page";
$totalRecords = $this->db->query($countsql);
$result["total_rows"] = $totalRecords->num_rows();
$query = $this->db->query($sql);
$result["list"] = $query->result_array();

Why i am getting datatype mismatch error?

SQLSTATE[42804]: Datatype mismatch: 7 ERROR: argument of WHERE must be
type boolean, not type integer LINE 1
$sql = "SELECT mod_modulegroupcode, mod_modulegroupname FROM module "
. " WHERE 1 GROUP BY `mod_modulegroupcode` "
. " ORDER BY `mod_modulegrouporder` ASC, `mod_moduleorder` ASC ";
$stmt = $DB->prepare($sql);
$stmt->execute();
$commonModules = $stmt->fetchAll();
$sql = "SELECT mod_modulegroupcode, mod_modulegroupname, mod_modulepagename, mod_modulecode, mod_modulename FROM module "
. " WHERE 1 "
. " ORDER BY `mod_modulegrouporder` ASC, `mod_moduleorder` ASC ";
$stmt = $DB->prepare($sql);
$stmt->execute();
$allModules = $stmt->fetchAll();
$sql = "SELECT rr_modulecode, rr_create, rr_edit, rr_delete, rr_view FROM role_rights "
. " WHERE rr_rolecode = :rc "
. " ORDER BY `rr_modulecode` ASC ";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":rc", $_SESSION["rolecode"]);
$stmt->execute();
$userRights = $stmt->fetchAll();
You are getting a datatype mismatch error because the where clause of a SQL statement expects you to provide conditions, not integer values. Your third query has a condition for its where clause, but your first two try to just give an integer value. There are some programming languages where 1 treated like "true", but SQL is not one of those languages.
Given that you're assembling the SQL with your code, if there's no condition to provide for the where clause, then just leave the where clause out, like this:
$sql = "SELECT mod_modulegroupcode, mod_modulegroupname FROM module "
. " GROUP BY `mod_modulegroupcode` "
. " ORDER BY `mod_modulegrouporder` ASC, `mod_moduleorder` ASC ";
But then you're going to have a problem because mod_modulegroupname is not aggregated. Since you're not doing any aggregation, I suggest just taking the GROUP BY clause out, too. You should also take the backticks out of your order by. This would leave you with:
$sql = "SELECT mod_modulegroupcode, mod_modulegroupname FROM module "
. " ORDER BY mod_modulegrouporder ASC, mod_moduleorder ASC ";
If I can kindly say so, it sounds like you should do a SQL tutorial.

Explode element limit and Order By using

I wanna make this select with ORDER BY element and Limit Element But i cant solve it .. please help me..
I am doing a php chat bot tha find something on my database and reply ..but when i am selecting data it select many data in on time . thats whyy i nedd limit
$aKeyword = explode(" ",$keyword);
$query ="SELECT * FROM reply_key WHERE reply_key_value like '%" . $aKeyword[0] . "%' ";
for($i = 1; $i < count($aKeyword); $i++) {
if(!empty($aKeyword[$i])) {
$query .= "OR reply_key_value like '%" . $aKeyword[$i] . "%' ";
}
}
You can add order by id desc and then limit 1 to get the latest record, however, you can remove that "desc" if you want the oldest record.
$query ="SELECT * FROM reply_key WHERE reply_key_value like '%" . $aKeyword[0] . "%' " ORDER BY id desc LIMIT 1

MySQL syntax error in string built by PHP

I have some code which generates a MySQL query string called $query:
$query = "select * from Surveys where surveylayoutid='$surveyid' and customerid='" . $_SESSION['login_customerid'] . "' and (";
$clue = $_POST['postcode'];
$onwhat="Postcode";
$query .= $onwhat . " like '%$clue%') order by id desc";
$result = mysql_query($query, $connection) or die(mysql_error());
This returns something like:
select * from Surveys where surveylayoutid='12' and customerid='1' and (Postcode like '%dn%') order by id desc
which works fine. I've then altered the code because I want to search on more fields so it now reads:
$remap = array("Postcode", "Street", "HouseNum", "District", "Town");
$query = "select * from Surveys where surveylayoutid='$surveyid' and customerid='" . $_SESSION['login_customerid'] . "' and (";
for ($i=0; $i<=4; $i++) {
if ($_POST[strtolower($remap[$i])]!="") {
$clue = $_POST[strtolower($remap[$i])];
$query .= $remap[$i] . " like '%$clue%') order by id desc";
break;
}
}
This also returns:
select * from Surveys where surveylayoutid='12' and customerid='1' and (Postcode like '%dn%') order by id desc
which on the face of it is identical but it generates this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'like '%dn%' order by id desc' at line 1
In both cases $query contains the same "text" but for some reason isn't treated as a valid MySQL query in the updated code, can anyone tell me why?
One possible problem could be the interpretation of the content here.
If you use:
$query .= $remap[$i] . " like '%$clue%') order by id desc";
All that is inside "" gets to be interpreted. Thus there could be unwanted side effects that you don't see at first glance and can explain what is happening. To avoid this it would have to be changed to:
$query .= $remap[$i] . ' like ' . "'" . '%' . $clue . '%' . "') order by id desc";
Even though more clunky in terms of how big it is, it makes sure that $lue and also the % are not interpreted as all in between ' ' is not interpreted.
See if this help you solve your problem?
$remap = array(
"Postcode",
"Street",
"HouseNum",
"District",
"Town"
);
for ($i = 0; $i <= 4; $i++)
{
if ($_POST[strtolower($remap[$i]) ] != "")
{
$query = "select * from Surveys where surveylayoutid='12' and customerid='1' and (";
$clue = $_POST[strtolower($remap[$i]) ];
$query.= $remap[$i] . " like '%$clue%') order by id desc";
$query_done[] = $query;
unset($query);
$result = mysql_query($query_done[$i], $connection) or die(mysql_error());
// Display your result here
}
}
I tried changing your code abit, and it seems the result is something like this
select * from Surveys where surveylayoutid='12' and customerid='1' and (Postcode like '%Postcode%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (Street like '%Street%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (HouseNum like '%HouseNum%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (District like '%District%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (Town like '%Town%') order by id desc

jQuery and php. mysql error

My code loads with the following text on top of it:
"Problem with SQL: SELECT * FROM table WHERE id < ORDER BY id DESC LIMIT 5"
Could someone help me find a solution?
Thanks
//jQuery
var value = '3';
$.post("load.php", {number: value} ,function(data){
$('p').append(data);
});
$('p').load('load.php');
//PHP load.php
//I have the escape inside $db.
$random = $_POST['number'];
$db->query('SELECT * FROM table WHERE id <' . '$random' . 'ORDER BY id DESC LIMIT 1');
$result = $db->get();
foreach ($result as $key => $value){
echo $value['user'];
};
//Output
Problem with SQL: SELECT * FROM table WHERE id < ORDER BY id DESC LIMIT 5
$value['user']
Try changing it to this one:
$db->query("SELECT * FROM table WHERE id < " . $random . " ORDER BY id DESC LIMIT 1");
Better use double instead of single quotes.
The reason this is not working is because single quotes does not allow PHP to expand the variable value.
So instead of this:
$db->query('SELECT * FROM table WHERE id <' . '$random' . 'ORDER BY id DESC LIMIT 1');
You might do this:
$db->query('SELECT * FROM table WHERE id <' . $random . ' ORDER BY id DESC LIMIT 1');
Just remove the quotes in $random and you'll be well.

Categories