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();
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.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With