问题
I have been given this assignment, to include some sort of filtering to my current SQL query via User Input. Basically, i am looking for a filtering option, whether its some kind of menu or button, really doesn't matter. My mssql is as follows:
SELECT TOP 10 Test_Database.Distributor, Test_Database.Value
FROM Test_Database
WHERE Test_Database.Week = '(USER INPUT GOES HERE)'
GROUP BY Distributor
ORDER BY Value desc
How can i make the WHERE statement a User Input? For instance.. A client wants to see the given value of some distributor, but in the week/month/year of the clients choice.
Regards
回答1:
You can do that simply by introducing if else statement
$where = "";
//receive filter option example $_GET['week']
//Do some sanitizing for $_GET['week']
if ($_GET['week']) {
$where = "WHERE Test_Database.Week = $_GET['week']"
} else if (somecondition) {
$where = "some query";
}
//You can add multiple condition by concatenating $where, but make sure where not repeats
$query = "SELECT TOP 10 Test_Database.Distributor, Test_Database.Value
FROM Test_Database
$where
GROUP BY Distributor
ORDER BY Value desc "
回答2:
i m not sure but maybe you can try.
<input type="text" name="week"/>
Post this textbox value in select page and set that value in where close.
回答3:
there should not be ANY data from user in sql query
that did not pass filter
sql-injection is not an empty word
so no $_GET['week'] in sql if you didn't clear it
来源:https://stackoverflow.com/questions/14603807/php-mssql-filtering-from-user-input-html