问题
hey i am a beginner in PHP and MYSQL, i am stuck with a basic problem. How can i make my query from URL parameters
MY URL EXAMPLES:
www.abs.com/index.php?cat=shoes
www.abs.com/index.php?cat=shoes&subcat=sports
www.abs.com/index.php?cat=shoes&subcat=sports&color=blue
How can i handle this kind of URL's in my query, that is just my example query, i have a large set of fields for both of my tables. I need help with the WHERE part of query, main problem is i am passing (cat) in my URL where it is (b.category) in my database.
MY QUERY:
select a.p_id, a.p_name, a.p_prize, b.p_id b.color, b.category, b.subcategory
FROM products a INNER JOIN details b ON a.p_id=b.p_id
回答1:
First you need to process the URL using PHP by assigning the URL parameters to PHP variables:
$cat = $_GET['cat'];
$subcat = $_GET['subcat'];
$color= $_GET['color'];
Then you can use these variables to create a MySQL query string:
$queryString = "SELECT a.p_id, a.p_name, a.p_prize, b.p_id b.color, b.category, b.subcategory
FROM products a INNER JOIN details b ON a.p_id=b.p_id WHERE b.category = '" . mysql_real_escape_string( $cat ) . "' AND b.subcategory = '" . mysql_real_escape_string( $subcat ) . "' AND b.color = '" . mysql_real_escape_string( $color ) . "' ";
You can then use this query sting to query the database.
回答2:
This is easy enough:
$cat = $_GET['cat'];
$query = "SELECT a.p_id, a.p_name, a.p_prize, b.p_id b.color, b.category, b.subcategory
FROM products a
INNER JOIN details b ON a.p_id=b.p_id
WHERE b.category = '" . mysql_real_escape_string(trim($cat)) . "'";
Please note a couple of things, firstly the use of mysql_real_escape_string to help protect your database. It helps protect against SQL injections, although isn't entirely foolproof.
Also note that MySQL_* is depreciated. You shouldn't be writing queries in it any more. You should look into MySQLi or PDO.
来源:https://stackoverflow.com/questions/22074954/create-mysql-query-from-url-get-parameters