4

I am making a query like this:

$b1 = $_REQUEST['code'].'A'; //letter 'A' is concatenated to $_REQUEST['code']
$a = $_REQUEST['num'];
echo $b1.$a;
$sql = "SELECT '".$b1."' FROM student_record1 WHERE id=".$a;
$result = mysql_query($sql);
if(!$result)
{
    echo '<p id="signup">Something went wrong.</p>';
}
else
{
    $str = $row[0]
    echo $str;
}

Here $b1 and $a are getting values from another page. The 'echo' in the third line is giving a correct result. And I am not getting any error in SQL. Instead, I am not getting any result from the SQL query. I mean echo at the last line.

1
  • Have you tried outputting what $sql contains? Also, see above. Commented Nov 3, 2011 at 5:35

2 Answers 2

4

Don't do this, it breaks your relational model and is unsafe.

Instead of having a table with columns ID, columnA, columnB, columnC, columnD, columnE and having the user select A/B/C/D/E which then picks the column, have a table with three columns ID, TYPE, column and have TYPE be A/B/C/D/E. This also makes it easier to add F/G/H/I afterwards without modifying the table.

Secondly, with the extra column approach you don't have to build your SQL from input values like that. You can use prepared statements, and be safe from SQL Injection. Building SQL from unfiltered strings is wrong, and very dangerous. It will get your site hacked.

Sign up to request clarification or add additional context in comments.

8 Comments

A rare guest on this site - a sensible answer.
A much more robust solution. +1 to you sir or madam
okk... thank u... actually i am not greately aware of this sql injections... can u suggest me some good source to steady them...
@yaswanthchilukuri: You should start by reading what SQL Injection is, Wikipedia is good enough for that. Only after you understand how the vulnerability manifests, you can start protecting yourself from it. Use the libraries that exist, don't invent your own (it will fail). Since you seem to be using PHP, you will be using mysql_real_escape_string or prepared statements.
I agree it does not help with field names, but since I don't think the field names solution is a good one, I proposed an alternative. If you must use field names, a whitelist is the best option.
|
2

If you must use dynamic table/column/database names, you'll have to run them through a whitelist.

The following code will do:

$allowed_column = array('col1', 'col2'); 
$col = $_POST['col']; 
if (in_array($col, $allowed_column)) { 
    $query = "SELECT `$col` FROM table1 "; 
} 

See: How to prevent SQL injection with dynamic tablenames?

For more details.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.