Jump to content

Modifying a query


okrobie

Recommended Posts

Hello, I have a query: $sql = "select id, first_name, last_name, teacher from table where id='$_SESSION[user_id]'";

 

but instead of  "id='$_SESSION[user_id]'" I want the where statement to say: where id=(a number specified in the URL)

Like this http://www.mydomain.com/myfile.php?user_id=53

where 53 is the number of the id I want.

 

How do I accomplish this? Thanks for your help.

Link to comment
Share on other sites

Here, Note the security to sanitize (escape) the string should be needed on all user input:

$sql = "SELECT id, first_name, last_name, teacher FROM table WHERE `id`='" . mysql_real_escape_string($_GET['user_id']) . "'";

 

Queries should generally be neat (Commands in capitals and column names in backticks) for readability/maintainability, and escaping really should be done before the query. Here is some more info on the subjects

 

mysql_real_escape_string

http://dev.mysql.com/doc/refman/5.0/en/security.html

http://www.bitrepository.com/sanitize-data-to-prevent-sql-injection-attacks.html

http://www.tizag.com/mysqlTutorial/mysqlquery.php

Link to comment
Share on other sites

Thanks oni-kun, The only problem is I don't know what to put for the real escape string. (mysql_real_escape_string) What additional information do I need to give you? Regards, okrobie

 

Only the variable, In this case the $_GET['user_id'] which is gotten from the URL. Take a look at this example:

//Grab user ID from url and apply escaping:
$userid = mysql_real_escape_string($_GET['user_id']);

//Use user ID in query:
$sql = "SELECT id, first_name, last_name, teacher FROM table WHERE `id`='$userid' ";

 

Consider this malicious url: http://www.domain.com/myfile.php?user_id=20' and DROP TABLE table

 

It would change the query (The single quote) and thus allow malicous SQL code to be injected. mysql_real_escape_string sanitizes and nullifies the effects of the single quite thus allowing the query to be secure, that's all that's needed.

Link to comment
Share on other sites

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.