5

I have an application that goes by that passes for my PHP a variable (nomecardapioBD and which received and recorded in the variable :nomecardapioBD) which is the table name that I want to select all rows and columns.

But to receive the variable via post can not make the appointment. Can anyone tell me what was wrong with this part of my code ?

$query = "Select * FROM :nomecardapioBD "; $query_params = array( ':nomecardapioBD' => $_POST['nomecardapioBD'] ); //execute query try { $stmt = $db->prepare($query); $result = $stmt->execute($query_params); } catch (PDOException $ex) { $response["success"] = 0; $response["message"] = "Database Error!"; die(json_encode($response)); } // Finally, we can retrieve all of the found rows into an array using fetchAll $rows = $stmt->fetchAll(); 
1
  • 2
    Table and Column names cannot be replaced by parameters in PDO. Commented May 31, 2016 at 7:13

2 Answers 2

3

Why not this?

$query = "Select * FROM " . $_POST['nomecardapioBD']; //execute query try { $stmt = $db->prepare($query); $result = $stmt->execute(); } catch (PDOException $ex) { $response["success"] = 0; $response["message"] = "Database Error!"; die(json_encode($response)); } // Finally, we can retrieve all of the found rows into an array using fetchAll $rows = $stmt->fetchAll(); 

You should also do some sort of input sanitization though.

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

7 Comments

This answer is an SQL injection itself. Wonder why it was so much upvoted.
@YourCommonSense I didn't mean to provide an industry standard solution. I showed the OP a way to resolve his issue. And I made the last statement to suggest him against the danger.
You showed the wrong way.
I rolled back your edit because it made your answer even worse.
This question is already closed as a duplicate with a link to the answer with a proper solution. but if you are curious what was wrong with your edit, I'll explain that: you see, whatever escape_string function is essentially fro the strings only. While escaping an identifier wi th it will do no help and will not stop an injection, while giving you a false feeling of safety.
|
2

Table and Column names cannot be replaced by parameters in PDO. Just use it as

$table=$_POST['nomecardapioBD']; $query = "Select * FROM $table"; //execute query try { $stmt = $db->prepare($query); $result = $stmt->execute(); } catch (PDOException $ex) { $response["success"] = 0; $response["message"] = "Database Error!"; die(json_encode($response)); } 

1 Comment

You should have been voted to close this question instead of posting an insecure answer that leads to SQL injection.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.