0

So i am filtering my content using the following function:

 $queryAll = 'SELECT * FROM :tbl WHERE :column BETWEEN :year AND :endyear';
    $queryAll_exec = $pdo->prepare($queryAll);
    $results = $queryAll_exec->execute(
        array(
            ':tbl'=>$tbl,
            ':column'=>$column,
            ':year'=>$year,
            ':endyear'=>$endyear

        )
        );

Then i check the $result var to see if the query went through and send the object back to the page to call for a fetch there. The problem is, my query is not even going through, I tried checking if it was a mistype on my Query and tested on PHPMyAdmin with the correct values and it does go through. I think it may be a problem with php sending my INTs as strings on the BETWEEN operator.

This is a little bit more of my code for better context:

function getMoviesByFilter($filter,$tbl){
    $pdo = Database::getInstance()->getConnection();
    $year = '19'.$filter;


    if($tbl =='tbl_movies'){
        $column = 'movies_year';
    }elseif($tbl=='tbl_series'){
        $column = 'series_year';
    }

    $endyear = $year + 9;

This is where i call this function , the information does go through correctly, so I know this is not the issue.

if(isset($_GET['filter'])){
        $filter = $_GET['filter'];

        $tbl = 'tbl_movies';

        if(isset($_GET['series'])){
            $filter = $_GET['filter'];
            $tbl = 'tbl_series';
        }

        $getMovies = getMoviesByFilter($filter,$tbl);

    }


For anyone that find this answer, the workaround i used once i understood that you cannot bind tables and columns, I used this:

if($tbl =='tbl_movies'){
        $queryAll = 'SELECT * FROM tbl_movies WHERE movies_year ';
    }elseif($tbl=='tbl_series'){
        $queryAll = 'SELECT * FROM tbl_series WHERE series_year ';
    }
    $endyear = $year + 9;

    $queryAll .= 'BETWEEN :year AND :endyear';    
    $queryAll_exec = $pdo->prepare($queryAll);
    $results = $queryAll_exec->execute(
        array(
            ':year'=>$year,
            ':endyear'=>$endyear

        )
        );
  • 1
    You can't bind to a table or column name. You will need to include `$tbl` and `$column` into the query string, but make sure that you appropriately sanitise them (e.g. using a whitelist) first. – Nick Apr 10 '20 at 22:51
  • Thank you very much, Sorry for the double posting, Couldnt find it because I was looking for the wrong problem. – guilhermebueno6 Apr 10 '20 at 22:52
  • It's no problem at all - the important thing is you have an answer to your problem. – Nick Apr 10 '20 at 23:26

0 Answers0