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".
Related
I have table in database named ads, this table contains data about each ad.
I want to get that data from table to display ad.
Now, I have two choices:
Either get all data from table and store it in array, and then , I will treat with this array to display each ad in its position by using loops.
Or access to table directly and get each ad data to display it, note this way will consume more queries to database.
Which one is the best way, and not make the script more slow ?
In most Cases #1 is better.
Because, if you can select the data (smallest, needed set) in one query,
then you have less roundtrips to the database server.
Accessing Array or Objectproperties (from Memory) are usually faster than DB Queries.
You could also consider to prepare your Data and don't mix fetching with view output.
The second Option "select on demand" could make sense if you need to "lazy load",
maybe because you can or want to recognize client properties, like viewport.
I'd like to highlight the following part:
get all data from table and store it in array
You do not need to store all rows into an array. You could also take an iterator that represents the resultset and then use that one.
Depending on the database object you use this is often the less memory-intensive variant. Also you would run only one query here which is preferable.
The iterator is actually common with modern database result objects.
Additionally this is helpful to decouple the view code from the actual database interaction and you can also defer to do the SQL query.
You should minimize the amount of queries but you should also try to minimize the amount of data you actually get from the database.
So: Get only those ads that you are actually displaying. You could for example use columnPK IN (1, 2, 3, 4) to get those ads.
A notable exception: If your application is centered around "ads" and you need them pretty much everywhere, and/or they don't consume much memory, and/or there aren't too many adds, it might be better performance-wise to store all (or a subset) of your ads in an array.
Above all: Measure, measure, measure!
It is very, very hard to predict which algorithm will be most efficient. Often you implement something "because it will be more efficient" only to find out later that your optimization is actually slowing down your application.
You should always try to run a PHP script with the least amount of database queries possible. Whenever you query the database, a request must be sent to the database (usually) over the network, and your script will idle until the request came back.
You should, however, make sure not to request any more data from the database than necessary. So try to filter as much in the WHERE clause as possible instead of requesting the whole table and then picking individual rows on the PHP layer.
We could help with writing that SQL query when you tell us how your table looks and how you want to select which ads to display.
I've searched this relentlessly and I cannot find an answer to my quandary - I think the problem is that I'm not exactly sure WHAT to search for! Anyhow, my problem is this...
Scenario:
Imagine having a database of, for arguments sake, recipes and you wanted to give users the ability to generate a list of recipe suggestions based on various criteria.
In the form of a web page, I would want this to be a series of drop down boxes on the left. The user would select their filter options from the drop down boxes and, after pressing the submit button, would be presented with a list of recipes that fit the criteria.
So they could, for example select 'Meal Type', 'Calories', 'Cooking Time' and then (after hitting submit) get back a list of recipe suggestions that fit the bill.
(Ideally they would appear without the need for reloading the page and would be contained within a slider to browse through, but I can probably crack that part if I get the underlying part sorted...)
Requirement:
I just need to know - at a top level - which technologies I would use to achieve this (and the process of how they work together).
I'm guessing I'd need a MySQL dB with recipes that are tagged with criteria, then use the form and php to pull from the database. Is this correct?!
Seems like such a common requirement, but I can find no good reading on how to achieve this..
Take a look at the PHP guide to prepared statements. You'll be basically writing a select statement against the table where your data resides, with the where clause of the select statement being the parameters selected by your user in the form.
PHP Prepared Statements
The reason you want to stick to prepared statements is that they are generally more secure against attacks on your site via the form, using SQL injection.
For the end to end solution, your front end will submit to a PHP page which will then handle the criteria specified by the user, translating those into the prepared statement which will find the data from your table. The table itself will need to have columns which correspond to the criteria. That gets more into database design which is a much larger topic to cover here, however there are plenty of guides out there for that.
Really you want to break the solution down into the subcomponents, then find various guides out there to tackle the parts. Good luck, hope this helps. :)
The process:
1) User makes selection and clicks submit button. That will initiate a HTTP POST to a PHP page (can be the same PHP page) where you would collect these information.
2) Open a MySql database connection with PHP. You would need to know SQL to pull data from MySql DB. Depending on how your database schema is laid out.
3) Once you pull this information display them as a checkbox where user can click.
This is the bare minimum.
If you wanna get a bit more fancy you can use JQuery ajax post (http://api.jquery.com/jQuery.post/) so the page does not refresh.
Good luck and I'm already hungry. haha.
When the user selects options in your form and submits it, this will run a PHP script on the server. The server retrieves the option parameters, and uses them to construct a SQL query. For instance, the script might contain something like:
$criteria = array();
if (isset($_POST['calories'])) {
$criteria[] = 'calories < '.$_POST['calories']);
}
if (isset($_POST['time'])) {
$criteria[] = 'cooking_time < '.$_POST['time']);
}
...
$query = 'SELECT * FROM recipes WHERE '.implode(' AND ', $criteria);
You use a library like mysqli or PDO to perform the query and get the results. Then you loop through the results, and format them into an HTML table which will be returned to the user as the resulting web page.
Or the PHP script could return the results as JSON data. Your web page could use AJAX to get this data from the server, then use JavaScript to format it into a table.
Basically I'm looking to create a page using PHP that will take SQL input, and output the results returned by the DB (MySQL). This is not for a production website (I understand the security implications). It's more for learning and practice. Kind of like the SQL console section of phpMyAdmin, or even similar to what sqlzoo.net can do (I think they are using perl, but I'd like to do it in PHP). Is there a practical way to accomplish this?
For example, how can I create a page in PHP/HTML to display a table of results when I don't know how many columns the query will return?
Also, what is the most practical way to allow a visitor to this web page to restore the DB to a default state with the original data? (e.g. create a sql dump of the original state and make a button that runs it? or is there a better way?)
Thanks!
Use * in your SQL query to fetch all columns and loop over the results from mysql_fetch_row() or mysql_fetch_assoc() with foreach.
Besides that, have you thought of using the mysql CLI ? It's useful for those requirements.
This question should be more specific than it is now.
"create a sql dump of the original state and make a button that runs it?" - Yes. But make sure you drop/delete the existing data.
You may have to run at least two queries... first return one row using LIMIT 1, and count the returning elements (using PHP count($row) if you use mysql $row = fetch_row($handle) ) to count the columns, and you can use SQL COUNT() to find out how many rows would be returned.
As for returning data to original state, I think a drop/recreation from a dump like you said may be the simplest and most reliable option.
Your best option is just running the query, checking if the amount of rows > 0, and then if it is, loop through the query resultset in a foreach and just show whatever you like.
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)
I am trying to paginate the results of an SQL query for use on a web page. The language and the database backend are PHP and SQLite.
The code I'm using works something like this (page numbering starts at 0)
http://example.com/table?page=0
page = request(page)
per = 10 // results per page
offset = page * per
// take one extra record so we know if a next link is needed
resultset = query(select columns from table where conditions limit offset, per + 1)
if(page > 0) show a previous link
if(count(resultset) > per) show a next link
unset(resultset[per])
display results
Are there more efficient ways to do pagination than this?
One problem that I can see with my current method is that I must store all 10 (or however many) results in memory before I start displaying them. I do this because PDO does not guarantee that the row count will be available.
Is it more efficient to issue a COUNT(*) query to learn how many rows exist, then stream the results to the browser?
Is this one of those "it depends on the size of your table, and whether the count(*) query requires a full table scan in the database backend", "do some profiling yourself" kind of questions?
I've opted to go with the COUNT(*) two query method, because it allows me to create a link directly to the last page, which the other method does not allow. Performing the count first also allows me to stream the results, and so should work well with higher numbers of records with less memory.
Consistency between pages is not an issue for me. Thank you for your help.
There are several cases where I have a fairly complex (9-12 table join) query, returning many thousands of rows, which I need to paginate. Obviously to paginate nicely, you need to know the total size of the result. With MySQL databases, using the SQL_CALC_FOUND_ROWS directive in the SELECT can help you achieve this easily, although the jury is out on whether that will be more efficient for you to do.
However, since you are using SQLite, I recommend sticking with the 2 query approach. Here is a very concise thread on the matter.
i'd suggest just doing the count first. a count(primary key) is a very efficient query.
I doubt that it will be a problem for your users to wait for the backend to return ten rows. (You can make it up to them by being good at specifying image dimensions, make the webserver negotiate compressed data transfers when possible, etc.)
I don't think that it will be very useful for you to do a count(*) initially.
If you are up to some complicated coding: When the user is looking at page x, use ajax-like magic to pre-load page x+1 for improved user experience.
A general note about pagination:
If the data changes while the user browses through your pages, it may be a problem if your solution demands a very high level of consistency. I've writte a note about that elsewhere.