-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– Lucas Bittencourt
Hello Lucas! You can clarify better where is the problem in bindParam?
– Felipe Nascimento
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
– Lucas Bittencourt
Thanks for the answer, Lucas! I read the documentation but did not understand that I could only use in this case.
– Felipe Nascimento
@Lucasbittencourt make your comment a response! This can help other people in the future :)
– Rafael Tavares