Reputation: 63
I have a url like this:
http://www.nearbynursinghomes.com/innerpage.php?state=CA&city=RIVERSIDE&shop=ALTA%20VISTA%20HEALTHCARE%20&%20WELLNESS%20CENTRE
I'm currently using this code:
$category = $_GET["state"];
$city= $_GET["city"];
$shop= $_GET["shop"];
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $results_per_page;
$sql = "SELECT *
FROM $datatable
WHERE STATE='$category'
AND CITY='$city'
AND PROVNAME='$shop'
ORDER BY PROVNAME ASC LIMIT $start_from, $results_per_page" ;
$rs_result = $conn->query($sql);
However it doesn't return the proper value because of the &
in the middle of the value which says shop=ALTA%20VISTA%20HEALTHCARE%20&%20WELLNESS%20CENTRE
.
It just gets cut off. How would I fix this?
Upvotes: 0
Views: 72
Reputation: 48041
You have a malformed querystring in your url. You should do everything in your power to correct this at its source.
If you are unable to do so, then a workaround is the best you can do.
This is not a particularly efficient method, nor a simple pattern (Pattern Demo), but it will work on your sample string.
You can leverage $_SERVER['REQUEST_URI']
or whatever you wish to capture your url, then use this preg_match()
method (PHP Demo):
$url=urldecode('http://www.nearbynursinghomes.com/innerpage.php?state=CA&city=RIVERSIDE&shop=ALTA%20VISTA%20HEALTHCARE%20&%20WELLNESS%20CENTRE');
if(preg_match_all('/(?<=[?&])([^=]+)=\K[^=]+(?=&|$)/',$url,$qs)){
// key------^^^^^^^ ^^^^^-------value
$array=array_combine($qs[1],$qs[0]);
var_export($array);
}
Output:
array (
'state' => 'CA',
'city' => 'RIVERSIDE',
'shop' => 'ALTA VISTA HEALTHCARE & WELLNESS CENTRE',
)
Then you can reference those array elements when you write your MySQLi prepared statements with placeholders.
If you are happy to access the other key-value pairs with $_GET
and only want to extract the shop
value then this is simple/direct way:
Code: (Demo)
$url = urldecode('http://www.nearbynursinghomes.com/innerpage.php?state=CA&city=RIVERSIDE&shop=ALTA%20VISTA%20HEALTHCARE%20&%20WELLNESS%20CENTRE&page=4');
echo preg_match('~[?&]shop=\K[^=]+(?=&|$)~', $url, $out) ? $out[0] : '[fail]';
Output:
ALTA VISTA HEALTHCARE & WELLNESS CENTRE
Upvotes: 1
Reputation: 63
After a good nights rest i came up with this solution using the tools provided here.
$shop= $_SERVER['REQUEST_URI'];
$shop= explode("=", $shop,4);
$shop= $shop[3];
$shop= urldecode("$shop");
Upvotes: 0