Display latest search results from MySQL with PHP - php

Google unfortunately didn't seem to have the answers I wanted. I currently own a small search engine website for specific content using PHP GET.
I want to add a latest searches page, meaning to have each search recorded, saved, and then displayed on another page, with the "most searched" at the top, or even the "latest search" at the top.
In short: Store my latest searches in a MySQL database (or anything that'll work), and display them on a page afterwards.
I'm guessing this would best be accomplished with MySQL, and then I'd like to output it in to PHP.
Any help is greatly appreciated.

Recent searches could be abused easily. All I have to do is to go onto your site and search for "your site sucks" or worse and they've essentially defaced your site. I'd really think about adding that feature.
In terms of building the most popular searches and scaling it nicely I'd recommend:
Log queries somewhere. Could be a MySQL db table but a logfile would be more sensible as it's a log.
Run a script/job periodically to extract/group data from the log
Have that periodic script job populate some table with the most popular searches
I like this approach because:
A backend script does all of the hard work - there's no GROUP BY, etc made by user requests
You can introduce filtering or any other logic to the backend script and it doesn't effect user requests
You don't ever need to put big volumes of data into the database

Create a database, create a table (for example recent_searches) and fields such as query (the query searched) and timestamp (unix timestamp that the query was made) said, then for your script your MySQL query will be something like:
SELECT * FROM `recent_searches` ORDER BY `timestamp` DESC LIMIT 0, 5
This should return the 5 most recent searches, with the most recent one appearing first.

Create table (something named like latest_searches) with fields query, searched_count, results_count.
Then after each search (if results_count>0), check, if this search query exists in that table. And update or insert new line into table.
And on some page you can just use data from this table.
It's pretty simple.

Ok, your question is not yet clear. But I'm guessing that you mean you want to READ the latest results first.
To achieve this, follow these steps:
When storing the results use an extra field to hold DATETIME. So your insert query will look like this:
Insert into Table (SearchItem, When) Values ($strSearchItem, Now() )
When retrieving, make sure you include an order by like this:
Select * from Table Order by When Desc
I hope this is what you meant to do :)

You simply store the link and name of the link/search in MySQL and then add a timestamp to record what time sb searched for them. Then you pull them out of the DB ordered by the timestamp and display them on the website with PHP.
Create a table with three rows: search link timestamp.
Then write a PHP script to insert rows when needed (this is done when the user actually searches)
Your main page where you want stuff to be displayed simply gets the data back out and puts them into a link container $nameOfWebsite
It's probably best to use a for/while loop to do step 3
You could additionally add sth like a counter to know what searches are the most popular / this would be another field in MySQL and you just keep updating it (increasing it by one, but limited to the IP)

Related

PHP + MySQL cascading searches from linked query results

Apologies in advance for the wall of text; not sure if this is possible but i thought i'd ask. I've looked online and can't quite find what i want. I have been learning a lot of PHP and MySQL and am at the stage where i am starting to write my own database driven websites. A freely available database i have been practicing with is the eve_sdd_crucible_11 database which is freely available from the game website. I have been using it because it's huge and requires the use of a lot of different skills to get the most out of it.
I would like to do a simple database for exploration. This database queries the main one for information, creates a new table based on the search results and also allows the user to add their own comments on what they have found. I have the various queries ready to go but because i don't want a massive user interface, i want to keep the user side as clean as possible. This app needs to query and display results from the 'mapregions', 'mapconstellations', 'mapsolarsystems' and 'mapdenormalize' tables and insert this information into a new database with the retrieved info plus a comment box for each entity.
Now the preamble is done, this is what i am looking to do:
Query 'mapregions' (region name returns region ID to be used in next query) and display results (linked)->
click on linked result, query 'mapconstellations' (constellation name returns constellation ID to be used in next query) and display results (linked)->
click on linked result, query 'mapsolarsystems' (solar system name returns solar system ID to be used in next query) and display results (linked) ->
click on linked result, query 'mapdenormalise' and display all entities in that system -> Inject content into new database along with comment boxes per listed entity.
Like i said earlier in the post, i have the queries set up ready to go, i have the beginnings of the php for the page but i am stuck on how to link these displayed results to the next query in the chain. All results have to display the name of the entity and it's the entity's corresponding ID number that is used to execute the next query in the chain.
Not sure if i've explained it particularly well, but it's the best i can do at this time of night... Any help or pointers would be vastly appreciated as it's starting to do my head in ;)
Need to look into joins - from reading through that text, it seems like you're missing a basic understanding of how to join tables - your 4th paragraph, to me, sounds like it should be a single query.
Creating a new database and/or table per search shows that you might still be missing some of the fundamentals - as that approach would never scale and would be a nightmare to manage.
Start reading up on mysql joins: Mysql Joins and go from there, looking at other examples of how joins work and real world examples - that will hugely affect how you continue building this.

creating analytics chart with php

i'm developing a web application with php and mysql. i have videos in my website, users can upload their videos.
Now, i want to increase the interactivity by creating simple analytics chart for the video views.
The graph chart will be containing the views for every month. The problem is i don't know where to begin with.
Can anybody tell me the logic to store the video views in the database of every month and then view in form of a bar chart? ( Like google analytics says the number of visitors every month or every week)
Google Charts will be perfect for what you are looking to do. I use them myself. Just output the stats with PHP json_encode.
Then use a cron job to fetch the current amount of veiws or other stats and store them in a data type text row.
https://developers.google.com/chart/
When to count a view?
You'll have to define when you count a view. Probably best would be to analyze the time gaps in which a certain user visited a video, how long it played and probably some identificators like his User-Agent, to be able to differenciate between several users behind an IP adress (if the user isn't logged in).
Inserting the view
Once you've decided if you count a view, you'll have to insert it into the database. This depends on what database and table structure you use. Have a look at a PHP MySQL Tutorial, or if you think you can do more, have a look PDO, which can be more secure and useful.
In order to be able to analyze monthly statistics, you'll have to insert each view with a timestamp. At the end, you'll just have to select the values for the specified date (in your case, the last month).
This requires that you at least know how to setup your database tables, in which you insert your data.
Showing the views
Since you'll have an entry for every view in you database, you're best shot is to create an automatic job, which updates another table with the total of the views. This will reduce the load, and also prevent your users from instantly seeing the view counts (might be helpful if someone is trying to bump view count --> he can't immediatly see if he's successfull).
Creating graphs
First you'll have to select the values. Let's say your user is able, to specify the date-range of which he wants to see the views, you'll have to take this range, query your database with it, and then proceed with the result. How you select it, depends on how you want to display it. If you want to show every single day of the month, you'll have to group the views by day.
How you actually display the data is open to you. It could be something really simple, something with tables, or you could use something like JpGraph to create graphs as images. I personally use JpGraph for stuff like that. Needs some working into, but it's worth the effort.
I hope this gave you somehow an idea how to solve your problem. If you have more specific problems, post some code and what you're trying to do, because that solution doesn't exist.
Have a table with columns video_id, count, month and year.
The video_id, month and year combined as an Unique Key.
Whenever a video is viewed (in programming terms requested) try to insert the video_id, 1, month and year.
Check whether you get a unique key violation. If you do then instead of inserting you update the count with count + 1.
To fetch the month and year you can use MYSQL Date functions.
video_id would be sent from the front end and count can be easily incremented.
Once you have this table you can always get the count for a specific video for that month and year combined.

Hyperlink Using Query

I have my Search Results being displayed just fine, but I have several categories. I want to be able to select the Column and use ORDER BY. Here's what I have to try and do this.
<a href='searchresult.php?db=members&table=people&sql_query=SELECT+%2A+FROM+%60people%60+ORDER+BY+%60lastname%60.%60level%60++DESC+%60AGAINST+$search&token=5e1a18b6cccb5db7a37bb3fce055801a'>Last Name</a>
the $search is what I search for. and when I look at the link it shows what I searched for in its place. So I figured this would work, but of course it did not. What would be the right way to set this up for each one of my columns so when I click the link it will sort my results in the order of that column?
Thanks!
The first thing that should SCREAM at you is to NEVER run any SQL query that contains any input that could possibly come from a client without first sanitizing it. Running an entire query from (potentially) user input will allow them to run a command like DROP DATABASE or TRUNCATE TABLE, or worse, they could get sensitive information out of it.
So you should hard-code your SQL query and just take the user input for the specific values you are querying for, but first sanitize those, by doing something like this:
$query = sprintf("SELECT * FROM 'people' ORDER BY %s DESC", mysql_real_escape_string($_GET["orderby"]));
Now, on to your actual question...after the page has been loaded, you have two options:
You could re-query using AJAX.
You could sort the table using Javascript.
Which is better really depends on how many rows you are expecting.
If you are fetching a lot of rows, sorting via Javascript starts getting pretty slow, but if it's just a few rows (like less than 100 or so), then Javascript is probably the way to go. I don't know much about other libraries, like JQuery or otherwise, not sure if they have a better solution. So for a lot of rows, using AJAX to just re-query the database is probably faster.
However, if your page consists of just this table by itself, there's not really any point in using AJAX as opposed to just refreshing the page with a different query.
If you do decide to sort the table using Javascript, a library like this one might help. Or just google "javascript sort table".

Basic version control for MySQL table

I'm trying to setup a (I thought) fairly simple versioning system for static html pages on a site. The goal is to keep previous versions of the content, then restore to them if needed (I guess basically creating a new version that's a duplicate of an old one), and optionally to toss out data older than X versions ago.
The table's setup is fairly straightforward:
id
reference_id (string/used to determine what page the item pertains to)
content (document/html page sized amount of data)
e_user (user who changed it last)
e_timestamp (when it was changed)
I just want to have something setup to create a previous version for each edit to the content, then be able to restore to it if needed.
What's the best method for accomplishing this? Should everything be in the same table, or spread across a few different ones?
I read through a few pages on the subject, but a lot of them seemed like overkill for what i'm trying to accomplish (ex http://www.jasny.net/articles/versioning-mysql-data/ )
Are there any platforms/guides about that will help me in this endeavorer?
Ideally you would want everything in the same table with something in your query to get the correct version, however you should be careful how you do this as an inefficient query will put extra load on your server. If normally you would select a single item like this:
SELECT * FROM your_table WHERE id = 42
This would then become:
SELECT * FROM your_table
WHERE id = 42
AND date < '2010-10-12 15:23:24'
ORDER BY date DESC
LIMIT 1
Index (id, e_timestamp) to allow this to perform efficiently.
Selecting multiple rows in a single query is more tricky and requires a groupwise-maximum approach but it can be done.
You can use a technique called "auditing". You would set up audit tables. Then you would either write it into your code or setup triggers on the DB side so that every time a change is made, an entry is added into the appropriate audit table. Then you can go back through the audit table and see things like:
"Oh, yesterday Sue went in and fixed a typo"
"Uh oh, steve wiped out an entire paragraph by accident earlier today while trying to rewrite this section"
Your primary table that stores the data doesn't keep all that data, so it can stay slim. If you ever need to look at that data and say roll stuff back, you can go look in your audit table and do that. You can setup the audit table however you want, so each audit row can have the entire content BEFORE edit, and not just what was edited. That should make "rolling back" fairly easy.
Add a version column and a delete column (bool) and create some functions that compare the versions of rows with the same id. You'll definitely want to be able to easily find the current version and the previous version. To get rid of the data you'll want to write another function that sorts all of the versions of id, figures out which are old enough to be deleted, and marks them for deletion by another function. You'll probably want to have an option to make certain pages immune to deletion or postpone it.

How to store search criteria or search results?

I have a php classifieds website (mostly) and I am currently using MYSQL as a database.
Later on I will use SOLR or maybe Sphinx as a "search engine".
I want to make it possible for users to view "results" of searches they have made before, but I don't know where to start...
How is this done?
Currently I have a form which is filled in and when submitted, the php just checks agains a mysql table to see if there are any matches.
Should I store the 'Search criteria' and do a new search every time the users click on one of their previous searches, or should I store the results? I would prefer to make a new search because new items may have been inserted since the last search!
If you need more input, just let me know and I will update this Q.
Thanks
Well... if you're basically talking about "saved searches", I'm doing something similar currently so that I just have a separate table where....
saved_search_id (primary) | user_id (foreign) | search_name | criteria1 | criteria2 | criteria3 ... etc
So basically I can now display to the user a list of saved searches they've created, and the table stores the criteria that were part of that search. I can then use those saved criteria to run a saved search anytime.
Does that help?
Use query-string parameters ($_GET) for the search form. Then the user can bookmark the search. If you want, you could create a bookmarking feature in your application, but there really is no need.
If you are concerned about performance, make sure that your database' cache settings are tuned correctly, and that you don't write too often to the table. MySql will do a good job of caching then.
You already have said it: if users should see the new results of old queries, you'll have to store the search parameters somehow and re-do the search when a users requests it.
Store the search criteria. This is quite obivious as if the data changes users will get old results. And consider the space the results might take after a while :)
I would also consider really storing the search criteria not the actual query. If you change the database the stored searches would still work as you need to update the query generation engine also but you would most likely forgot to update every stored query.

Categories