Take SQL input in PHP and output query results to the page - php

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.

Related

Fastest way to do a bulk fetch with PHP PDO and MySQL database

I'm using PHP with the PDO library to work with a MySQL database, and I am fetching several thousand rows from a database based on two of the fields. Specifically, I need rows corresponding to certain latitude-longitude pairs, if such points exist. Currently, I am making a prepared statement and executing it once per point/row. What is the fastest way to fetch many rows like this? Just use a bunch of OR's?
It's impossible to answer to such a broad question.
The most general answer would be like this:
If you have to do this regularly - say, on a live site on each user's click - then, you have to reduce the number of parameters queried.
If it's just occasional operation - just leave it as is.
In other words, you don't need "fastest". You need "fast". Or even "reliable".

Hierarchical commenting system in threaded view: PHP and MySQL

I have the need to render a threaded view of a 2-levels hierarchical commenting system. The comments are stored in a database. The information about the hierarchy is given by field 'parent_id' (which is 0 for the top-level comments). I cannot change the structure of the database.
The present solution is by means of multiple SQL queries:
an SQL query is performed to fetch all top-level comments
the code loops through the top-level comments and for each of them performs an SQL query to fetch its children
Now I wonder if a solution with only one SQL query to fetch all the comments as they are followed by the code suggested here to sort them by threads could be more efficient.
Any reccomendation?
Thanks,
Luciano
I've done similar scripts and from my point of view it's better to do a first query to fetch all the 'parents' (parent_id==0) and then for each one of them do another query to get all its 'sons' information.
If you have to retrieve a HUGE ammount of threats using a single query you have to wait for the query to complete to work with the data. If you divide the search in different and smaller queries you can start formating and printing them before looking for the 'sons'. Also doing it in a single query could make the query slower since using more tables in the same query could make it halt due to a lock_table when someone is creating a new threat.
Another solution, which I would only recommend if the query is very slow due to being forced to use multiple JOINs or using WHERE with non-indexed fields (you should never do that, but if you can't change the database...), is to retrieve ALL the threats in a single query (both parents and sons, without any of those WHERE or JOIN that makes the query slower) and then organize them using PHP. This is by no means practical, and you should never use this method unless the time to complete the query is very long.

Whichever make the script more slowly (I have two choices)

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.

Is there a way using php to take a mysql query result

Is there a way using php to take a MYSQL query result, get a value from a column in the first record fetched, and then put that record back into the query result so when when looping over the result set later, that record can be used again? If this is possible, can I put the record back in the first position again?
Or should I return the value that I need from that first row as a separate variable in my routine in MYSQL. If this would be the better route to take, can someone give me some insight on how to return both a query result set and a separate variable as well? I cannot seem to get this to work either.
Or would the best way to do this be to create my own array from the query result set and then manipulate the mysql result set as need? I'm trying to stay away from this just to cut out the step of creating that array if one of the above two options is possible, otherwise I will just go with this.
Thanks in advance.
Just before you need to loop through again, you could use mysql_data_seek($query, 0);
Then the next call to fetch will be the first row again.
I haven't personally used it, but that's what I understood from the php manual:
http://us.php.net/manual/en/function.mysql-data-seek.php
I agree with the answers above but just to state it a slightly different way:
There is no point rewinding a pointer inside the query result object. You have to keep track of where it is, and it's easy to mess up, and it isn't worth the tiny speed increase.
It's much better to make a copy of the entire array and access the records using keys. Much easier to keep track of what is going on.

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".

Categories