The keys for $_POST are filled by the name attributes of your form fields. [] does indicate that the form will send an array of data.
The values for $_POST are the value attribute of the form field, which for certain form fields (like a checkbox) have a default value, and for others (like a text input) is variable.
In the above part If my understanding of the basic PHP is not wrong then $table act as a counter.
$_POST[“table”] have 4 items. that means $table stands as a placeholder variable to which values will be assigned from array as the loop will run 4 times(assuming all checkboxes are ticked otherwise number will be different based on 3 of checkboxes ticked).
$table can be anything such as $anything.
correct me if I am wrong part of my understanding.
In general this is true, but in this case, $table should be a string - a table name, that corresponds to the value of the checkbox from your form.
In practice, you should be careful with this form of query construction; you should be using prepared statements properly to execute your query, rather than a literal string query, which is what you’re doing now.
What I mean is, if we knew nothing about the variables, then this statement is true:
foreach ($anarray AS $avalue) {
“$avalue can be anything”
This is true, $avalue could be anything - a string, a number, another array, anything.
But in your example, you know what $table SHOULD be - on each iteration of the loop it should be a string, and that string should be a table name in your database. (Note, I use the word ‘should’ here, because we don’t know for a fact that it is, because we haven’t sanitized the input.
If I sent your webpage a $_POST[‘table’] value that says 'table1'; DROP TABLE cars;, what happens to your database?
So, if $table is 'table1'; DROP TABLE cars;, your $show_table_query becomes: "SHOW CREATE TABLE 'table1'; DROP TABLE cars;"
This is perfectly valid SQL - it’s two queries. The first returns a query description of the table, the second deletes the cars table from the database.
This is the very basic form of SQL injection. It’s also what prepared statements are designed to prevent.
I think the point is that if you use prepared statements instead of just concatenating strings into your query string, that will have the effect of sanitising the input.