I have a database with some info and some html code that generates a report of the data in the database, based on the sql query in开发者_JAVA百科 the code. I would like users to be able to use a form to extract only certain data without having to change the sql query manually. How can I do this?
My form has 3 fields (branch code, ip address and serial number) which i would like to use as a search criteria for the information that should be displayed in the report.
When a users types in the branch code for instance, the form should adapt the sql query to display only that specific branches info.
You can programatically create a SQL query based on input from the user - but you need to be careful how you do it. Directly accepting input from the user and including it in a SQL statement is generally considered to be a bad idea, especially if you don't validate / sanitise it properly.
One alternative is using prepared statements (assuming you're using MySQL): http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html
There are also lots of libraries floating around that help with SQL, including verification / sanitisation.
From what you've said, when the form is posted to the page you can check to see which part of the form has been filled in, and execute a prepared statement / build your own statement from that. Just make sure you do it in a safe way.
You will probably need something like
SELECT branchcode, ipadr, sn FROM sometable WHERE branchcode = "'.$_POST['branchcode'].'"';
Learn more here: http://www.tizag.com/phpT/forms.php
edit: But this could be dangerous in a productive environment. Google for sql injection to learn more.
精彩评论