Jump to content

Recommended Posts

I'm working on using a MySQL query to return some resutls based off getting part of the URL from a previous page.

 

 

URL sample:

 

<a href="http://site.com/file.php?alabama">Alabama</a>
 

 

MySQL Query sample:

 

$query = "select items from table_name where state = '$_GET[state]';
 

 

Which will then query the database based off the state name and then spit out an array with the data, etc.

 

I'm not too sure what the "safest" way to accomplish this is though since I've been informed that this will lend to possible SQL injection.

 

Any suggestions on how to escape this properly?

Link to comment
https://forums.phpfreaks.com/topic/276496-best-use-of-_get-with-a-url/
Share on other sites

First is to make sure you're using the PDO or mysqli extensions. Not the mysql extension (whose functions are all named mysql_*) because it's old and not as useful.

 

Once you've switched, PDO and mysqli both support prepared statements where you can write a query with variables

select items from table_name where state = ? (mysqli)
select items from table_name where state = :state (pdo)
and then bind the state name to that variable. Then you don't have to worry about SQL injection at all: no need to quote stuff, no need to escape stuff. Edited by requinix

Yes, then you do a mysqli::prepare(), mysqli_stmt::bind_param(), and mysqli_stmt::execute(). (Then fetch the results.)

 

Take a look at mysqli in the manual. Besides the documentation there's plenty of examples and user comments.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.