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();
Saty
  • 22,443
  • 7
  • 33
  • 51

2 Answers2

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.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
hashbrown
  • 3,438
  • 1
  • 19
  • 37
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));
}
Saty
  • 22,443
  • 7
  • 33
  • 51