开发者

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

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 开发者_JAVA技巧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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜