1

I've been learning about prepared statements and binding parameters... I had hoped to be able to do this:

SELECT ? FROM table WHERE id=?

However, I found you can't use a bound parameter to call the table or columns where searching here. And I understand the reason behind why as well now after searching here.

That leaves me with this question. Is it safe to use a variable like this:

$fields = "col1, col2, col3";  
SELECT $fields FROM table WHERE id=?

I ask, because I have a large statement, and it's nice to be able to make the statement short and use $fields which contains a very long string. I could just use select all, except that I'm then storing and then binding the results (not sure if it's necessary actually... I haven't tried to use $stmt->get_result() yet, just upgraded php to be able to use it yesterday).

I have a general idea of how SQL Injection works, and from all the reading I've been doing it seems the idea of a prepared and parametrized statement is it prevents SQL Injection by having SQL not run the whole statement, but breaks it apart to put it simply...

Yet when I put the $fields variable, is that opening it back up to SQL Injection now that I have a variable directly in the statement? $fields is hard coded, not coming from any source other than the code itself (not from user, not from database). I don't know the extent to which SQL Injections can potentially attack, which is why I'm asking here. I can deal with a long statement, but this will help me understand the proper way as well make it more secure.

Thank you.

matts
  • 6,405
  • 1
  • 28
  • 48
MikeCxt
  • 45
  • 4

2 Answers2

5

$fields is hardcoded, not coming from any source

This means you do not have to worry about injections at all. Even if you were using it in any other place of the statement.

You should of course be carefull not to make it "public" later on!

colburton
  • 4,559
  • 2
  • 21
  • 36
0

To prevent SQL injection in your query avoid to put that variable directly into the query. Instead of that you should use PDO

See this question

Community
  • 1
  • 1
Ronak Patel
  • 5,083
  • 7
  • 44
  • 122