sanainfotech
sanainfotech

Reputation: 691

how to use prepare select statement with variable

$colName = rent_due_date

I am trying to use $colName as my column name and run SELECT statement with that column name.

How can I use $colName in a prepared SELECT statement and echo $row[$colName]?

<?php
$colName =  $_GET['colName'];
$smt = $pdo->prepare('SELECT * FROM dhr WHERE ? < curdate()');
$smt = $pdo->bindParam(1,$colName);
if($smt){
if($smt->execute()){
while($row = $smt->fetch()){ 
?>
// echo in the table as below   
<td class="center "><?php echo $row[$colName];?></td>

Error

Call to undefined method PDO::bindParam()

Upvotes: 1

Views: 347

Answers (1)

meda
meda

Reputation: 45500

  • You can only bind parameter on the statement object not the PDO connection. That's why you are getting Fatal error: Call to undefined method PDO::bindParam()
  • You cannot bind column names as placeholders

so change:

$colName =  $_GET['colName'];
$query = "SELECT * FROM dhr WHERE $colName < NOW()";
echo $query;
$smt = $pdo->prepare($query);
if($smt){
echo "prepare() sucess\n";
$result = $smt->execute();

    if($result){
    echo "execute() sucess\n";
    $data = $smt->fetchAll(PDO::FETCH_ASSOC);
    var_dump($data);
    //display table
    }else{
    echo "execute() failed\n";
    }
}else{
echo "prepare() failed\n";
}

Upvotes: 1

Related Questions