Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, MY SQL error query [duplicate]

Tags:

php

mysql

pdo

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();
like image 306
Gustavo Melo Avatar asked May 31 '16 07:05

Gustavo Melo


2 Answers

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.

like image 145
hashbrown Avatar answered Oct 17 '22 06:10

hashbrown


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));
}
like image 36
Saty Avatar answered Oct 17 '22 06:10

Saty