I have a friend who runs an online auction website. He currently has a featured items section on the homepage that he wants to have cycle an item every X amount of minute. The site runs off a MySQL database which I haven't actually seen yet.
The current code that he is using is a big, long messy Javascript code that is causing all kinds of errors.
The items would have to cycle in order and when they get to the end, go back and repeat again.
What would be the best approach to take to this using PHP?
EDIT: I mean from a backend SQL perspective. Not the UI.
Thanks
Ben
Assuming you have a separate table for the featured items (probably has an item ID referencing the main items table and maybe other info)... In this table, add a last_featured column to represent the time the item was last shown. From there, you can manipulate your queries to get a rotating list of featured items.
It might look something like this (as a weird pseudocode mix between PHP & MYSQL):
// select the most recent item in the list, considered the current item
$item = SELECT * FROM featured_items ORDER BY last_featured DESC LIMIT 1;
if ($item['last_featured'] > X_minutes_ago) {
// select the oldest item in the list, based on when it was last featured
$item = SELECT * FROM featured_items ORDER BY last_featured ASC LIMIT 1;
// update the selected item so it shows as the current item next request
UPDATE featured_items SET last_featured=NOW() WHERE item_id = $item['item_id'];
}
Note that this requires 3 call to the database... There may be a more efficient way to accomplish this.
Related
I have a webgallery (made with laravel) and would like to add the possibility to reorder the images... Now, I have thought of several approaches but for every aproach i find that there should be a better way of doing it.
the gallery does not use javascript, so ones changes have been made it needs to be sumbitted and reloaded to reflect the changes
The main difficulties are:
how to store the order in the database? an additional Integer column?
how to add a picture "between" two others?
how to handle it at a frontend level?
So far the best ideas I had are these:
a column with integers, order by clause on this column. Frontend: a move up and a move down button.
problems of this solution: it needs a refresh after each single movement. it needs to identify the previous/next picture and swap the number with that one. To move a single pic from the end of the gallery to the top it takes forever.
a column with integers, automatically prefilled in steps of 100, order by this column + upload time in case of same numbers, Frontend: a textbox where the user can specify the integers for each picture and a submit button.
problems of this solution: does not look very professional. solves all the problems of the previous solution
same as previous solution but with double values to be able to insert pictures without limits.
They all dont seem the real deal.. Any sugestion on how to do it properly is welcome. thanks
I have done that kind of sorting in OpenCart products list (custom backend design)
Sort order was additional column order INT(11) in database
We had 3 input fields: up/down/custom
Where custom was dropdown of all indexes from 1 to max-items.
All inputs does the same:
Take new order value and shift all elements except itself. Up or down shift depends if you move element to front or to back of current position
UPDATE order FROM products SET order = :newOrder WHERE id = :currentItemId
if ($newOrder > $oldOrder)
UPDATE order FROM products SET order + 1 WHERE order >= :newOrder AND id != :currentItemId
else
UPDATE order FROM products SET order - 1 WHERE order <= :newOrder AND id != :currentItemId
Inserting does the same update, just first query becomes INSERT INTO
To get rid of ugly refresh of page on every action we do Ajax requests and re-sorted DOM with jQuery
On my First SQL-Based Project.
I want a News pane on my website.
In that news pane. I want to show Latest 10 News of all time which I keep updating after every new change in website like a changelog.
What will be the workaround for SQL-PHP to Show only the Latest 10 News and How would I update the DataBase Table (Removing the Oldest, 10th Entry) and then Adding Latest(1st Entry) to the table + changing the IDs (1-10).
For this, You can Make a Table(e.g. News). With Column ID content date.
Simply Add the news and the do this.
SELECT * FROM News ORDER BY ID DESC LIMIT 10
then,
Take this into PHP ARRAY and then simply work there.
Rarely would you want to remove the old values from your database straight after adding a new entry, why not just order the database select results and limit the rows, far more flexible for future code changes.
SELECT * FROM News ORDER BY id DESC LIMIT 10;
Assuming that you have timestamp for your news, you might want to order by this database value instead. As this would allow you to 'bump' up news articles later on, for example if you want an edited article to be considered new you would just have to update the timestamp, and not change the row ID to a higher value.
SELECT * FROM News ORDER BY unix_time_stamp DESC LIMIT 10;
Finally if you wanted to clean up your news entries I would do that on a cleanup function separately, probably on some kind of hourly or daily cronjob.
I am trying to sort the information given to me by the API of an engineering journal. I have extracted the following information into a table:
ID (integer),
Journal Entry Name (Text),
Description (Text),
Page Length (integer),
Has Media (boolean)
Each "Journal Entry" has only one ID associated with it. Each ID also has other characteristics that are not returned by the API but that I want to use to sort. They are:
Category (Things like Econ, Math, Biology. Each ID can have more than one category)
Boolean values (Things like requiring special subscriptions)
I have created a second table in the following format:
ID (integer),
Category (text),
Boolean1 (bool),
Boolean2 (bool),
Boolean3 (bool)
Since each ID can have more than one category, when this occurs another row is added to this table. The idea being that any given row only has one ID and one category in it.
What I want to do is this:
Be able to find the top ten categories when it comes to
Highest Journal Entry (ID) count
Highest Total Page Length
Highest Journal Entry count where the "Has Media" boolean is true
Create a means of navigating like "pagination" where each page shows the nth results of the aforementioned top ten.
So if I chose to Highest Journal Entry count method, the first page would be show IDs, Names, and Descriptions of all the Journal entries in the category with the highest count.
My plan has been to create a new table where the numbers one through ten are in the first column, and then populate the second column with the top ten categories. Then I can use a process similar to pagination in which the nth page only shows the values with the corresponding category from the original value. However I can't seem to be able to make this top ten list/matrix, nor do I know if it there is a better way.
Unfortunately I am not a MySQL or PHP coder by trade, and have only gotten this far by lots and lots of googling. I have been completely unable to find any guides for a navigation method like the one I want. And since I don't know the proper terminology, I am just trying random google searches at this point.
Is this the best way to go about it? Or would it be better to create a third table of some sort? Is there perhaps an easier way to do this with something that can use the PHP and MySQL code I already wrote?
Not sure I really understand what you're going for here, but my best guess is that you probably want to combine your two initial tables and have category be a set rather than an individual term so you can have a single entry per unique ID.
Then you'd just need to write calls for each of your top ten finds as needed. Since each id can have an unknown number of categories I would start with a limit of 10 and then process the returns starting with the top match, grab its categories, if there are more than 10 grab the first 10, if there are less than 10 grab what there are, update the amount you're looking for (if there were 4 then you're now looking for 6), and move on to the next best match.
Maybe something like this:
categories = null;
$delimeter = ',';
$count = 1;
$top10 = array();
$result = mysql_query("
SELECT *
FROM table_name
ORDER BY page_length DESC
LIMIT 10");
while($row = mysql_fetch_array($result) && $count <=10)
{
$categories = $row['categories'];
$id = $row['id'];
$splitcontents = explode($delimeter, $catagories);
foreach($splitcontents as $category){
if (!in_array($catagory,$top10)){
$top10[$count] = array(
'category'=>$category,
'journal_id'=>$id
);
$count++;
}
}
}
I'm trying to create a filter to show certain records that are considered 'trending'. So the idea is to select records that are voted heavily upon but not list them in descending order from most voted to least voted. This is so a user can browse and have a chance to see all links, not just the ones that are at the top. What do you recommend would be the best way to do this? I'm lost as to how I would create a random assortment of trending links, but not have them repeat as a user goes from page to page. Any suggestions? Let me know if any of this is unclear, thanks!
This response assumes you are tracking up votes in a child table on a per row basis for each vote, rather than just +1'ing a counter on the specific item.
Determine the time frame you care about the trending topics. Maybe 1 hour would be good?
Then run a query to determine which item has the highest number of votes in the last hour. Order by this count and you will have a continually updating most upvoted list of items.
SELECT items.name, item_votes.item_count FROM items
INNER JOIN
(
SELECT item_id, COUNT(item_id) AS item_count
FROM item_votes
WHERE date >= dateAdd(hh, -1, getDate()) AND
## only count upvotes, not downvotes
item_vote > 0
group by item_id
) AS item_votes ON item_votes.item_id = items.item_id
ORDER BY item_votes.item_count DESC
You're mentioning that you don't want to repeat items over several pages which means that you can't get random ordering per request. You'll instead need to retrieve the items, order them, and persist them in either a server-wide or session-specific cache.
A server-wide cache would need to be updated every once in a while, a time interval you'll need to define. Users switching page when this update occurs will see their items scrambled.
A session-specific cache would maintain the items as long as the user browses your website, which means that the items would be outdated if your users never leave. Once again, you'll need to determine a time interval to enforce updates.
I'm thinking that you need a versioned list. You could do the server-wide cache solution, and give it an version (date, integer, anything). You need pass this version around when browsing the latest trends, and the user will keep viewing the same list. Clicking on the Trends menu link will send them to the browsing pages without version information, which should grab the latest from your cache. You then keep this as long as the user is browsing these pages.
I can't get into sql statements, not because they are hard, but we don't know your database structure. Do you keep track of individual votes in a separate table? Are they just aggregated into a single column?
Maybe create a new column to record how many views it has? Then update it every time someone views it and order by threads with the largest number of views.
I have searched everywhere but could not get anything. The scenario is that when I run a select statement from MySQL/PHP, I want to use Next & Previous buttons to navigate backwards and forward through the results.
Does anyone know how I can accomplish this?
Here's how I run the query: select everything from members where hair = black;
This returns 8 results, and I have a page like so details.php?id=3 which takes id and display the details.
I want to be able to keep clicking the next button and move to another id from the result.
How do I accomplish this?
Thank you for your assistance.
If you mean to display 1 product details per page with Next buttons, then
1) Get the total rows from table
2) Find total number of pages like
$totalPages = $totalRows; //since 1 record per page
3) Loop thru $totalPages value to generate next links
4) Get the id of product from page url $_GET
5) Query sql using te product id obtained frm GET
Well thats the basics, hope your get it
Assuming you have all ids in the $allIds var, try something like this:
<?php
$id = (int) $_GET['id'];
$key = array_search($id, $allIds);
$nextId = $allIds[$key+1];
?>
Well, you have 2 different scopes here to address, first, when you query you are in PHP/Server side mode. PHP gets some data, processes it, shows some of it to the knowledge i have of your problem and then sends it to the browser.
Next, you have the client scope, where the client has the HTML rendered to his screen and has the possibility to click NEXT and PREVIOUS. When he does that, he issues a request to the server to get the NEXT or PREVIOUS record based on the current one.
You have 2 scenarios to work this problem out:
1) Load the whole data into memory and scan it to find your current position, see if there is a NEXT and PREVIOUS element and respond to the request of the user. If the user asked for the NEXT, easy, just move one more record. If the user asked for PREVIOUS item, then when scanning using a WHILE or FOR/FOREACH, always keep in memory the "lastitem" you saw, you can use this "lastitem" as your PREVIOUS item.
2) In the event you have many (i mean like more than 1000) items, you need to use a little subquery magic and work this out using SQL.
select everything from members where hair = black AND id = XYZ ORDER BY id LIMIT 2;
This will return you the CURRENT AND NEXT elements. Then call the same query again but this time, order it DESC so that your 2 items are the CURRENT AND PREVIOUS.
select everything from members where hair = black AND id = XYZ ORDER BY id DESC LIMIT 2;
Note that you can order this the way you want, the goal is to get a static result, something that always gets out the same way so that you can reverse it and get the items around the selected one.
I hope this helps you