Problem using PDO::bindParam with table names

Asked

Viewed 70 times

-1

I am a beginner in programming and wrote a code in php to practice PDO. However, I had a problem: when I use the Mysql command without bindParam it works normally. When I reference the table name using bindParam, the search returns null. Can you help me here? Follow the two examples:

That’s how it works:

<?php
$conn = new PDO("mysql: host=localhost;dbname=dbphp7","root","root");
$stmt = $conn->prepare("SELECT * FROM tb_usuarios");
$stmt->execute();
$results = $stmt->fetchALL(PDO::FETCH_ASSOC);
echo json_encode($results);
?>

Thus the search result is null:

<?php
$tabela = "tb_usuarios";
$conn = new PDO("mysql: host=localhost;dbname=dbphp7","root","root");
$stmt = $conn->prepare("SELECT * FROM :tab");
$stmt->bindParam(":tab",$tabela);
$stmt->execute();
$results = $stmt->fetchALL(PDO::FETCH_ASSOC);
echo json_encode($results);
?>
  • You can’t use the bindParam thus

  • Hello Lucas! You can clarify better where is the problem in bindParam?

  • 1

    You can only use this in values that will be inserted/updated/deleted/read in sql, for example: SELECT * FROM tb_usuarios WHERE usuario_id = :usuario_id

  • Thanks for the answer, Lucas! I read the documentation but did not understand that I could only use in this case.

  • @Lucasbittencourt make your comment a response! This can help other people in the future :)

1 answer

1

In addition to the comment of Lucas Bittencourt explaining that it is not possible to use bindParam with table names, I found this question here in Stackoverflow where it was well explained this question: https://stackoverflow.com/questions/182287/can-php-pdo-statements-accept-the-table-or-column-name-as-parameter

My goal was to write a method that would search for an X table in the database. An alternative to bindParam is to write a string outside of "prepare" by concatenating the variable with the name of the chosen table and then sending the Mysql command ready by that string through a variable. Something like:

<?php

class Sql extends PDO {    
    public function __construct() {
        parent::__construct("mysql: host=localhost;dbname=dbphp7","root","root");
    }    
    public function buscaTabela($comandoSql) {
        $stmt = $this->prepare($comandoSql);
        $stmt->execute();
        $results = $stmt->fetchALL(PDO::FETCH_ASSOC);
        echo json_encode($results);
    }    
}

$tabela = "tb_usuarios";
$comandoSql = "SELECT * FROM ".$tabela;
$busca = new Sql;
$busca->buscaTabela($comandoSql)

?>

I appreciate the help and hope to help someone with the same doubt.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.