Adding LIMIT to a query - php

I'm trying to edit a query and add LIMIT to it and it's taking a while. Can you help me out a little?
Here's the working query:
$result = mysql_query("SELECT * FROM events INNER JOIN event_performers ON events.ID = event_performers.eventID WHERE event_performers.performerID = '898' ORDER BY events.ID");
I want to add LIMIT ' . $offset . ', ' . $rowsPerPage to it but am getting errors.
Thanks in advance.

Limit should be placed at last like, "SELECT * FROM your_table LIMIT 0, 10" 0 is offset and 10 is row per page, may be it should be
mysql_query("SELECT * FROM events INNER JOIN event_performers ON events.ID = event_performers.eventID WHERE event_performers.performerID = '898' ORDER BY events.ID LIMIT ".$offset.", ". $rowsPerPage);

Related

How to Join Two MySQL query into a single array?

I have two mysql query as follows
$sql1 = mysqli_query($mysqli, "SELECT * FROM manualp WHERE client_id=75 AND date between '$currentdate' and '$prevdate' ");
$sql2=mysqli_query($mysqli, "SELECT * FROM manualp WHERE client_id=75 order by date DESC LIMIT 1");
Is there any way i can join them together ? and get them in a array . For example
Both query are joined into $sql3 . I would like to post result having value $sql2 showing last
while($result = mysqli_fetch_array($sql3)) {
POST RESULTS HERE
}
Based on your comments, because you're using ORDER BY and LIMIT in your query, you actually need to wrap that second query in a subquery to perform a UNION.
SELECT * FROM manualp WHERE client_id=75 AND date between '$currentdate' and '$prevdate'
UNION
SELECT * FROM (SELECT * FROM manualp WHERE client_id=75 order by date DESC LIMIT 1) t1

MySQL 1 Table, 1 Select, Multiple Wheres

I am trying to add a "Related Products" section below my product. I can only get this to work if
I use two separate SELECTS. I am trying to combine them but can't get it to work.
Same Table in MySQL -
<?php
//select items from db
$items = mysql_query
("SELECT * FROM table WHERE (myinvno='dg300')
OR (action='alive' AND cate='dogs'
ORDER BY productNo ASC LIMIT 0, 4)");
or die(mysql_error());
while($item = mysql_fetch_array($items))
{
?>
This part is for the Related Products section:
OR (action='alive' AND cate='dogs'
ORDER BY productNo ASC LIMIT 0, 4)");
Thank you ~
The correct syntax would look like:
$items = mysql_query("
SELECT *
FROM table
WHERE (myinvno = 'dg300') OR
(action = 'alive' AND cate = 'dogs')
ORDER BY productNo ASC
LIMIT 0, 4"
);
You were missing a closing parent after 'dogs'.
EDIT:
Hmmm . . . I wonder if this is what you want:
SELECT *
FROM table
WHERE (myinvno = 'dg300')
UNION ALL
(SELECT *
FROM table
WHERE (myinvno <> 'dg300') AND
(action = 'alive' AND cate = 'dogs')
ORDER BY productNo ASC
LIMIT 0, 4
);
This gets all rows that match the first condition plus four more that match the second.

php selecting an order from a different mysql table

Hi I am trying to retrieve my topics from table topics but in my look up list I want the most recent active topic to be showing, all the comments are in different table. How could I do it that my list shows all the topics from the topics table but puts them in order according to the most recent date from the comments table?
$forums = mysql_query("select * from forumtopic where category='$who' order by date DESC LIMIT " . (($page - 1) * 10) . ", 10");
while($forum = mysql_fetch_array($forums))
{
so I want it to be like
$forums = mysql_query("select * from forumtopic where category='$who' and select from forumcomment where category='$who' but order by date from forumcomment DESC LIMIT " . (($page - 1) * 10) . ", 10");
while($forum = mysql_fetch_array($forums))
{
if that makes sense
I believe this is what you wanted to do:
SELECT * FROM forumtopic
WHERE category='$who'
ORDER BY FIELD( topic,
(SELECT topic
FROM forumcomment
WHERE category='$who'
ORDER BY date DESC))
LIMIT " . (($page - 1) * 10) . ", 10
The order by field lets you specify an order for the table forumtopic, which is ordered by most active, also I don't know the schema of your table so you have to change the names accordingly
EDIT - SIMPLER SOLUTION, JOIN THEN ORDER BY
SELECT forumtopic.topic FROM forumtopic
INNER JOIN forumcomment
ON forumtopic.topic = forumcomment.topic
WHERE category = '$who'
ORDER BY forumcomment.date DESC
LIMIT " . (($page - 1) * 10) . ", 10

Is it ok to query inside a while loop?

I have two tables in one database. I am querying the first table limit by 10 then loop the results. And inside the while loop, I am doing again another query using a data from the first query as a parameter. Here is an example of the script:
<?php
$con = mysql_connect(host,username,password);
mysql_select_db(game_server);
//My first query
$q1 = mysql_query('SELECT * FROM game_characters ORDER BY score DESC LIMIT 10');
while($character = mysql_fetch_object($q1)){
//My second query
$q2 = mysql_query('SELECT * FROM game_board WHERE id="'.$character->id.'"');
$player = mysql_fetch_object($q2);
}
?>
So if I have a result of 100 rows, then the second query will execute 100 times. And I know it is not good. How can I make it better. Is there a way to do everything in one query? What if there is another query inside the while loop where a data from the second query as a parameter is used?
P.S.: I am doing a rankings system for an online game.
You can do it in one query if you use JOINs.
SELECT * FROM game_board AS b
LEFT JOIN game_characters AS c ON b.id = c.id
ORDER BY c.score DESC
LIMIT 10
You can also use nested query
SELECT * FROM game_board AS b WHERE
id IN (SELECT id FROM game_characters AS c ORDER BY score DESC LIMIT 10)
You can also put all game_character.id into an array, and use
$sql = "SELECT * FROM game_board AS b WHERE b.id IN (" . implode(', ', $game_character_ids) . ")";
Why not using JOIN?
This way there will be no queries within the while loop:
$con = mysql_connect(host,username,password);
mysql_select_db(game_server);
//My first query
$q1 = mysql_query('
SELECT *
FROM game_characters gc
LEFT JOIN game_board gb ON gc.id = gb.id
ORDER BY score DESC
LIMIT 10
');
while($character = mysql_fetch_object($q1)){
// do Your stuff here, no other query...
}
A better approach here would be to collect all the IDs in a concatenated string str in form 'id1', 'id2', 'id3', ... and use:
select * from game_board where id in (str)
What about if you do something like the following:
<?php
$con = mysql_connect(host,username,password);
mysql_select_db(game_server);
//My first query
$q1 = mysql_query('SELECT * FROM game_characters ORDER BY score DESC LIMIT 10');
while($character = mysql_fetch_object($q1)){
//My second query
$characters .= " ' $character->id ' ,"
}
$q2 = mysql_query("SELECT * FROM game_board WHERE id in (substr($characters,0,strlen($characters - 2))");
$player = mysql_fetch_object($q2);
?>

How to link to the right page of a topic in a search result?

I have a search function in a forum where the search results will be displayed 10 at the time. The user can then look at the next or previous 10 search results. The results show different topics where the searched words are to be found. Everything works like I want it to.
The issue is when I want the user to be able to click a result and end up on the right page of that topic. For instance post nr 14 in a certain topic must be viewed on page 2 ( using LIMIT 10,10 in the SQL query on the topic page). I send the LIMIT parameter as a $_GET in the link.
How can I retrieve the row number of each topic in the results out of the total numbers of that specific topic when ordering by the date it was posted? Everything is always displayed in that order. I would like to use $nr = $nr-1; //and then
$limit = floor($nr / 10) * 10;
on that number to be able to send the right LIMIT parameter with the link in the search result.
Here's the PDO used to get the search results:
$query = 'SELECT t.topic_id, t.topic_cat, t.topic_subject, p.post_content, p.post_id, UNIX_TIMESTAMP(p.post_date) AS post_date
FROM posts p
LEFT JOIN topics t ON p.post_topic = t.topic_id
WHERE p.post_content LIKE :search OR t.topic_subject LIKE :search ORDER BY UNIX_TIMESTAMP(p.post_date) DESC LIMIT :start, :size';
$statement = $db->prepare($query);
$statement->bindValue(':search', '%'.$search.'%');
$statement->bindValue(':start', $start2, PDO::PARAM_INT);
$statement->bindValue(':size', $pagesize, PDO::PARAM_INT);
$statement->execute();
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$array[$row['topic_subject']][] = $row['post_id'];
$nr = count($array[$row['topic_subject']]) - 1;
echo '<div class="search_result"><div class="search_topic"><a href="topic_view.php?id=' . $row['topic_id'] . '&cat_id=' . $row['topic_cat'] . '
&start=' . floor($nr / 10) * 10 . '#anchor_' . $row['post_id'] . '">' . $row['topic_subject'] . '</a><span style="float:right;color:#696969">'
. date("M d, Y",$row['post_date']) . '</span></div><div class="search_post">' . $row['post_content'] . '</div></div>';
}
} $statement->closeCursor();
It is the start parameter in the link that I somehow need to grab in the query so I don't have to do a new DB call for each post_id in the while loop.
Assuming, that you only know, the ID of the post, I would go like this:
SELECT
count(*)
FROM
`posts`
WHERE
date <= ( SELECT date FROM `posts` WHERE post_id = '$id' )
ORDER BY
date DESC;
This will give you the number of row this post is. After that, just do some php code like:
$start = floor( $nr / 10 ) * 10;
$end = ceil( $nr / 10 ) * 10;
For multiple IDs:
SELECT topic_id, (
SELECT
count(*)
FROM
`posts`
WHERE
date <= ( SELECT date FROM `posts` u1 WHERE u1.topic_id = u2.topic_id )
) AS row
FROM
`posts` u2
WHERE
topic_id IN ( '$id1', '$id2', '$id3' )
ORDER BY
date DESC;
$query = 'SELECT :start as start, t.topic_id, t.topic_cat, t.topic_subject,
p.post_content, p.post_id, UNIX_TIMESTAMP(p.post_date) AS post_date
FROM posts p
LEFT JOIN topics t ON p.post_topic = t.topic_id
WHERE p.post_content LIKE :search OR t.topic_subject LIKE :search
ORDER BY UNIX_TIMESTAMP(p.post_date) DESC LIMIT :start, :size';
then access through $start = $row['start']
$nr = count($array[$row['topic_subject']])+$start - 1;
I had a problem as you said. I think this links is useful for you.
I have done these successfully, I hope be useful you:
1. http://www.awcore.com/dev/1/3/Create-Awesome-PHPMYSQL-Pagination_en
2. http://www.9lessons.info/2009/09/pagination-with-jquery-mysql-and-php.html

Categories