Walking through a variable within a link only works on the first word in verbose variables, why?

I have this code below. As you can see, I am passing two variables along with a link. The second variabye ( category

) works whenever it is one word, but some categories have two words or more, and then on the receiving php page where I select the variable, only the first word is selected.

Example: I pass this: Rims & Tires

Only this happens via:Rims

$display_table .= "<a href='../ad.php?ad_id=$row[ad_id]&category=$row[category]' target='_parent'>";

      

This is how I extract it in the receiving php file (which the link refers to):

$cat = $_GET['category'];
echo $cat; //displays only first word of multiple word categories.

      

+2


a source to share


2 answers


You need to use the correct encoding. For the request data use urlencode

:

"<a href='../ad.php?ad_id=".urlencode($row['ad_id'])."&category=".urlencode($row['category'])."' target='_parent'>"

      

And since the value &

inside the attribute value must also be correctly encoded (using htmlspecialchars

):

"<a href='".htmlspecialchars("../ad.php?ad_id=".urlencode($row['ad_id'])."&category=".urlencode($row['category']))."' target='_parent'>"

      



Writing the correct code makes things a lot harder and, using the variation above, is probably also a lot more unreadable. But you can split the steps like this:

$row['ad_id'] = urlencode($row['ad_id']);
$row['category'] = urlencode($row['category']);
$href = htmlspecialchars("../ad.php?ad_id=$row[ad_id]&category=$row[category]");
$display_table .= "<a href='$href' target='_parent'>";

      

And if ad_id is always a numeric value, you don't even need to apply urlencode

on it.

+2


a source


This should do it:



$display_table .= "<a href='../ad.php?ad_id=".urlencode($row[ad_id])."&category=".urlencode($row[category])."' target='_parent'>";

      

0


a source







All Articles