David Ng
David Ng

Reputation: 25

Why is fetching data from MySQL via URL not working when “ ” is in the URL?

I have a table in MySQL database with id, location, type, content columns. If fetching a specific row via id in the URL, e.g. domain.com/page.php?id=1 I can do this by:

$sql = "SELECT * FROM database_table WHERE id=" . $_GET["id"];
$rs = mysql_query($sql);    
while($row = mysql_fetch_array($rs)) {

echo $row['location'] . $row['type'] . $row['content'] ;    

However if I want to fetch it via the other rows in the URL, e.g. domain.com/page.php?location=paris&type=housing

I tried this replacing the first line of code above with this:

$strSQL = "SELECT * FROM database_table WHERE location=" . $_GET['location']
                                                         . "AND type=" 
                                                         . $_GET['type'] ;

the code does not work on this URL:

domain.com/page.php?location=paris&type=housing

but works with this URL (notice the " " between the row):

domain.com/page.php?location="paris"&type="housing"

My question: Is there anything I can do to make it such that I don't have to have the " " between rows in the URL in order for the query to work?

Upvotes: 0

Views: 898

Answers (1)

sridesmet
sridesmet

Reputation: 895

Change

$strSQL = "SELECT * FROM database_table WHERE location=" . $_GET['location'] . "AND type=" . $_GET['type'] ;

to

$strSQL = "SELECT * FROM database_table WHERE location='" . $_GET['location'] . "' AND type='" . $_GET['type'] . "'";

Make sure you sanitize your $_GET data though.. you are vulnerable to mysql injection attacks. Mysql_query is also deprecated, use PDO.

You'll be able to call your script without quotes in the url:

domain.com/page.php?location=paris&type=housing

Upvotes: 2

Related Questions