Is it possible to perform an SQL Injection attack where the malicious SQL is stored in a database table?

StackOverflow https://stackoverflow.com/questions/22748275

  •  24-06-2023
  •  | 
  •  

Question

I am trying to ensure I protect against SQL Injection properly.

If I had a MySQL table T1 containing a column C1, and the value stored in C1 for a row was some SQL, is there any SQL that could be stored that would be executed when it is selected?

If it contained "SELECT * FROM T2", then selecting C1 would just return that SQL string, but I am just wondering if there is any way that the SQL stored could be executed?

I wouldn't want to store unvalidated data from a user in a db table, such that when I select it, expecting it to be First Name or something like that, it executes some malicious SQL.

Thanks,

Paul

Was it helpful?

Solution

would be executed when it is selected?

No.

OTHER TIPS

would be executed when it is selected?

No, not if all you do is select the content.

You could executed the SQL only if you subsequently copy it into another string in an unsafe manner and execute that string as a query.

For example:

$sql1 = "SELECT name FROM users";
$name = $pdo->query($sql1)->fetchColumn();

// the following is unsafe:
$sql2 = "SELECT * FROM user_activity WHERE user_name = '$name'";
$stmt = $pdo->query($sql2);

This is called "second order SQL injection" and it's not uncommon. The fix is the same as for any other dynamic values in an SQL query: use query parameters.

$sql2 = "SELECT * FROM user_activity WHERE user_name = ?";
$stmt = $pdo->prepare($sql2);
$stmt->execute(array($name));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top