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.