Log in

View Full Version : PHP URL MySQL Issue



DigiplayStudios
09-25-2010, 02:10 PM
Okay,

So I have a page named profile.php which displays any users profile page with some of their details (grabbed from the MySQL database).

I have at the top of the profile.php page the following code:


<?php
include 'dbc.php';
$id = $_GET['id']; // get var from URL
$result = mysql_query("SELECT * FROM users WHERE id = $id");
$row_settings = mysql_fetch_array($result);
?>

So when I go to a page like profile.php?profile.php?id=1 for example it would then display the profile details for the user with ID number 1 in the MySQL database.

However, I want to be able to do that with the field 'user_name' in my MySQL table. So something like, profile.php?profile.php?user_name=ed and it finds the details for the user with the user_name matching 'ed'. How do I do this? It doesn't seem to work if I simply change all the details to user_name.

bluewalrus
09-25-2010, 02:20 PM
I think you need to use the like operator


mysql_query("SELECT * FROM users WHERE id like '$user'");

You also shouldn't take direct inputs from users into a sql statement this leave you open to sql injections.

DigiplayStudios
09-25-2010, 02:24 PM
I think you need to use the like operator


mysql_query("SELECT * FROM users WHERE id like '$user'");

You also shouldn't take direct inputs from users into a sql statement this leave you open to sql injections.

Thank you! It worked. :)

How would I secure it from SQL injections?

bluewalrus
09-25-2010, 02:31 PM
You can try out

http://php.net/manual/en/function.mysql-real-escape-string.php

I dont have mysql so I can't be sure how that works.

You also could use preg_replace, or str_replace to pull out values that could be used for injections ',--, etc.

fastsol1
09-25-2010, 03:46 PM
The best way to help avoid SQL injection on a input from a user is to use the mysql_real_escape_string() which adds \ to anything with single or double quotes to cancel them out.

This is the typical function used for such things but depending on what exactly the input you want is, you could also use int() which would strip everything except integers from the input. Again there are a few different ways but the first function I said is the typical.