Good day,
I have a problem with following code, I have to limit companies ID_CL (it`s outcome). I want to limit the display to the only one ID_CL (one because , right now it displays everything) is it possible ?
Sorry for stupid question, I usually don't work with mysql/php
{
//$size_h =1;
list($list_num, $size_w, $size_h) = $this->getImageDefSize('list');
//$table = TB_JOB." jb LEFT JOIN ".TB_CL." cl USING(".ID_CL.") ";
$table = TB_JOB." jb LEFT JOIN ".TB_CL." cl USING(".ID_CL.") ";
$field = "jb.".ID_JOB.", jb.job_code, jb.shop_name, jb.job_name, jb.intro, jb.video_url, jb.salary, jb.area_0, jb.area_1, jb.area_2, jb.biz_0, jb.biz_1, jb.biz_2, jb.emid, jb.tel, jb.email, jb.access, jb.nenshu_range, jb.sv_1, jb.company, jb.worktime, jb.holiday";
$field .= ", jb.rail_1_0, jb.rail_1_1, jb.rail_1_2, jb.rail_2_0, jb.rail_2_1, jb.rail_2_2, jb.free_1_0, jb.free_1_1, jb.free_2, jb.free_3, jb.moddate, jb.regdate, jb.contents, jb.qualification,jb.zip,jb.pfid,jb.address1,jb.address2";
$field .= ", cl.".ID_CL.", cl.cl_name, cl.business, cl.email AS client_email ";
//$field .= ", cl.".ID_CL.", cl.cl_name, cl.business, cl.email AS client_email ";
if (! empty($_SESSION["srch"]["new"])) {
$od = " ORDER BY jb.setdate DESC, cl.rank, jb.jobid ASC";
} else {
$od = " ORDER BY cl.rank, jb.moddate DESC, jb.jobid ASC";
}
//$total = $this->countTB($table, ID_JOB, $this->wh);
$total = $this->countTB($table, ID_JOB, $this->wh);
\
if ($total > 0) {
// $_SESSION["srch"]["idlist"] = $this->arrayTB($table, ID_JOB, $this->wh.$od);
$_SESSION["srch"]["idlist"] = $this->arrayTB($table, ID_JOB, $this->wh.$od);```
Yes, you can use MySQL LIMIT for this purpose.
According to your query, After , jb.jobid ASC you should add LIMIT 1
This will help you.
Related
I'm trying to order a list of items based on the amount of comments for each topic as shown below:
$page = $_GET['page'];
$query = mysql_query("SELECT * FROM topic WHERE cat_id='$page' LIMIT $start, $per_page");
if (mysql_num_rows($query)>=1)
{
while($rows = mysql_fetch_array($query))
{
$number = $rows['topic_id'];
$title = $rows['topic_title'];
$description = $rows['topic_description'];
//get topic total
$sqlcomment = mysql_query("SELECT * FROM comments WHERE topic_id='$number'");
$commentnumber = mysql_num_rows($sqlcomment);
// TRYING TO ORDER OUTPUT ECHO BY TOPIC TOTAL ASC OR DESC
echo "
<ul>
<li><h4>$number. $title</h4>
<p>$description</p>
<p>$topictime</p>
<p>$commentnumber</p>
</li>
</ul>
";
}
}
else
{
echo "<p>no records available.</p><br>";
}
What would be the best way to order each echo by $num_rows (ASC/DESC values)? NOTE: I've updated with the full code - I am trying to order the output by $commentnumber
The first query should be:
SELECT t.*, COUNT(c.topic_id) AS count
FROM topic AS t
LEFT JOIN comments AS c ON c.topic_id = t.topic_id
WHERE t.cat_id = '$page'
GROUP BY t.topic_id
ORDER BY count
LIMIT $start, $per_page
You can get $commentnumber with:
$commentnumber = $rows['count'];
You don't need the second query at all.
First of all you have error here
echo "divs in order from least to greatest "number = $num_rows"";
It should be
echo "divs in order from least to greatest number = " . $num_rows . "";
And about the most commented try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY column DESC/ASC";
Or if there is not count column try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY COUNT(column) DESC/ASC";
So, I've put in a favourite images table, and I can't figure out how to get it working properly
Basically, this is the setup:
ImageFavs
FavID, UserID, ImgID
ImageList
ImgID, SiteID
I'd like it to select 20 or so images from the favourites table, but only ones that match the siteid in the image list table
This is the code I have at the moment, but it dawned on me it'd select 20 images from favourites, then only display them if the matching site was actually checked.
#select matching sites
for($i=0;$i<count($sites)-1;$i++){
$siteinfo = explode("-",$sites[$i]);
$siteid = $siteinfo[0];
$sitegroup = $siteinfo[1];
$selection[$siteid]="exists";
if($i!=0){
$sqlextra .= " OR ";
}
else{
$sqlextra = "AND (";
}
$sqlextra .= "SiteID='".$siteid."'";
}
if(!empty($sqlextra)){
$sqlextra .= ")";
}
else{
$sqlextra = "AND SiteID='-1'";
}
#show favourites
if($_GET['f']==1){
$sql="SELECT * FROM ImageFavs WHERE UserID='".$_SESSION['User_ID']."' AND Active = '1' ORDER BY RAND() LIMIT 20";
#(rand is just me being lazy, eventually I'll figure out how to separate it onto pages)
$result = mysql_query($sql);
$num = mysql_numrows($result);
if($num>0){
while ($row=mysql_fetch_array($result, MYSQL_BOTH)){
if(empty($sqlextra2)){
$sqlextra2 = " AND (";
}
else{
$sqlextra2 .= " OR ";
}
$sqlextra2 .= "ImgID='".$row['ImgID']."'";
}
$sqlextra2 .= ")";
}
}
#don't show favourites
if(empty($sqlextra2)){
$sqlextra2 = " ORDER BY RAND() LIMIT 20";
}
$sql="SELECT * FROM ImageList WHERE Valid='1' ".$sqlextra.$sqlextra2;
This output $sql from this seems like it could be so much neater though, an example of it is like this
SELECT * FROM ImageList WHERE Valid='1' AND (SiteID='6') AND (ImgID='5634' OR ImgID='8229' OR ImgID='9093' OR ImgID='5727' OR ImgID='7361' OR ImgID='5607' OR ImgID='7131' OR ImgID='5785' OR ImgID='7339' OR ImgID='5849' OR ImgID='7312' OR ImgID='5641' OR ImgID='8921' OR ImgID='7516' OR ImgID='7284' OR ImgID='5873' OR ImgID='8905' OR ImgID='7349' OR ImgID='7392' OR ImgID='8725')
Also, while I'm here, would there be a non resource heavy way to count the number of favourites for a user per website?
It's not for anything big, just messing around on a personal website to see what I can do.
You can INNER JOIN your two tables to get the results you want. INNER is used when you want results from both tables. It's best to use aliases to keep your tables straight.
SELECT l.*
FROM ImageFavs f
INNER JOIN ImageList l ON f.ImgID = l.ImgID
WHERE l.SiteID = [your site ID]
AND f.UserID='" . $_SESSION['User_ID'] . "'
AND f.Active = '1'
ORDER BY RAND() LIMIT 20
To get a count by site you can use GROUP BY. I think this should get you that count
SELECT COUNT(f.ImgID)
FROM ImageFavs f
INNER JOIN ImageList l ON f.ImgID = l.ImgID
WHERE f.UserID='" . $_SESSION['User_ID'] . "'
AND f.Active = '1'
GROUP BY l.SiteID
you want to use "JOIN"
SELECT * FROM ImageFavs LEFT JOIN ImageList ON ImageFavs.ImgID = ImageList.ImgID WHERE ImageList.SiteID = <your_site_id>
This works-
//Assuming $site_id contains the site ID/
$query = "select *.IF from ImageFavs as IF, ImageList as IL where IL.ImgId = IF.ImgId and IL.SiteId = $site_id LIMIT 20"
I am using the following PHP and MySQL code to pull high score records out of a database, 5 above and 5 below the users score.
<?php
$dbcon = mysql_connect("localhost", "XXXX", "XXXX") or die(mysql_error());
mysql_select_db("tulesblo_koreangame", $dbcon) or die(mysql_error());
mysql_query("SET NAMES utf8");
$name = $_POST["name"];
$email = $_POST["email"];
$score = $_POST["score"];
$table = "";
$submit = "";
$input = "";
$newposition = $_POST['position'];
$position = mysql_query("(SELECT position
FROM highscore
WHERE score < '$score'
ORDER BY score DESC
LIMIT 1)");
if(!$name){
$gethigherrows = "(SELECT *
FROM highscore
WHERE score >= '$score'
ORDER BY score ASC
LIMIT 5)";
$getlowerrows = "(SELECT *
FROM highscore
WHERE score < '$score'
ORDER BY score DESC
LIMIT 5)";
$higherrows= mysql_query($gethigherrows);
$lowerrows= mysql_query($getlowerrows);
if(mysql_error())echo mysql_error();
while($row=mysql_fetch_array($higherrows))
{
$uppertable .= "<tr><td>$row[position]</td><td>$row[name]</td> <td>$row[score]</td></tr>";
}
$x = 0;
if (mysql_num_rows($lowerrows) > 0)
{ mysql_query("UPDATE highscore SET position = position + 1 WHERE score < '$score'")or die("update failed");
while($row=mysql_fetch_array($lowerrows))
{
if ($x == 0)
{$position = $row['position'];};
$x++;
$newpos = $row[position]+1;
$lowertable.= "<tr><td>$newpos</td><td>$row[name]</td> <td>$row[score]</td></tr>";
}
$input = "<tr><td id='position'>$position</td><td><input id='nameinput'type='text' /></td><td>$score</td></tr>";
$submit = "<br />Enter email if you want to receive a prize!<br /><input id='emailinput'type='text' /><br /><input id='submithighscore'type='submit' value='Submit'>";
}
$table .= "<table id='scoretable'><tr><th>Position</th><th>Name</th><th>Score</th></tr>";
$table .= $uppertable;
$table .= $input;
$table .= $lowertable;
$table .= "</table>";
$table .= $submit;
$table .= "<br /><span class='msg'></span>";
echo $table;
}else{ echo($newposition);
mysql_query("INSERT INTO highscore VALUES (NULL, '$score', '$name', '$email', '$newposition')");
}
?>
The only problem, as you can see, is that if there are several instances of the same score, as there are and inevitably will be, the positions get jumbled up. How can I select by score first but ensure that it grabs the positions in a sensible order?
EDIT: OK, using the following
$gethigherrows = "(SELECT *
FROM highscore
WHERE score >= '$score'
ORDER BY
position ASC
LIMIT 5)";
$getlowerrows = "(SELECT *
FROM highscore
WHERE score < '$score'
ORDER BY score DESC,
position DESC
LIMIT 5)";
I now get:
Which is better but the above scores really need to be 9,8,7,6,5
Honestly SQL fries my brain :P
You can specify more than one column in a ORDER BY clause.
ORDER BY score ASC, position DESC
First I would fix those SQL-injection holes:
$score = mysql_real_escape_string($_POST['score']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$sql = "(SELECT *
FROM highscore
WHERE score >= '$score'
ORDER BY score ASC, position DESC
LIMIT 5)";
If you don't I can substitude ' or (1=1) LIMIT 1 UNION SELECT password, email, username FROM users -- for score. To get a list of all passwords and email addresses of your users.
How can I combine these two queries into one so I don't have to repeat the same lines again and again?
if(empty($cat_id))
{
$sql = "
SELECT *
FROM root_category_contacts
ORDER by cat_order ASC
";
$items_category = $connection->fetch_all($sql);
}
else
{
$sql = "
SELECT *
FROM root_category_contacts
WHERE root_category_contacts.cat_id != ?
ORDER by cat_order ASC
";
$items_category = $connection->fetch_all($sql,array($cat_id));
}
I don't need WHERE clause when I don't have the cat_id.
Is it feasible?
Test if ? is null or equals cat_id. Something like this:
Edit based on xdazz's comment. And assuming that cat_id > 0
$sql = "
SELECT *
FROM root_category_contacts
WHERE root_category_contacts.cat_id != ?
ORDER by cat_order ASC"
if(empty($cat_id)) {
$cat_id = 0;
}
$items_category = $connection->fetch_all($sql,array($cat_id));
if(empty($cat_id)) $where = "";
else $where = "WHERE root_category_contacts.cat_id != '$cat_id'"
$sql = "
SELECT *
FROM root_category_contacts
$where
ORDER by cat_order ASC
";
$items_category = $connection->fetch_all($sql);
I have a query
public static function TestQuery(
$start=0,
$limit=0){
$sql = "
SELECT count(*) AS total
FROM db.table1
JOIN db.table2
ON table1.fieldID = {$fieldID}
AND table2.assigned = 'N'";
$qry = new SQLQuery;
$qry->query($sql);
if($row = $qry->fetchRow()){
$total = intval($row->total);
}
return $total;
}
which works fine but when I add the limit as below, then it doesnt work and gives me errors
public static function TestQuery(
$start=0,
$limit=0){
$sql = "
SELECT count(*) AS total
FROM db.table1
JOIN db.table2
ON table1.fieldID = {$fieldID}
AND table2.assigned = 'N'";
//this fails
if($recordlimit > 0) $sql .= "LIMIT {$startRecord}, {$recordLimit} ";
//
$qry = new SQLQuery;
$qry->query($sql);
if($row = $qry->fetchRow()){
$total = intval($row->total);
}
return $total;
}
Any help will be appreciated
Put a space in front of LIMIT:
" LIMIT {$startRecord}, {$recordLimit} "
without the space you sql will result in a syntax error.
Edit: This is answer is not correct! MySQL will not error without a space before LIMIT (however, earlier versions of phpmyadmin will incorrectly parse such sql).
Your variables are called $limit and $start:
if($limit > 0) $sql .= " LIMIT {$start}, {$limit} ";
Try changing
if($recordlimit > 0) $sql .= "LIMIT {$startRecord}, {$recordLimit} ";
To
if($recordlimit > 0) $sql .= " LIMIT {$start}, {$limit} ";
It looks like your SQL is getting squished together and should be getting a bad syntax error, and you had the wrong (seemingly) variable names in there.
Wrong variables
if($recordlimit > 0) $sql .= "LIMIT {$startRecord}, {$recordLimit} ";
Solved
Thanks