skip to Main Content

I am creating a movie database and I have a query that finds movies by their ID and it is working.

public function getMovieById($id) {
        $query = "SELECT * FROM movies WHERE id = ?";
        $paramType = "i";
        $paramValue = array(
            $id
        );
        
        $result = $this->db_handle->runQuery($query, $paramType, $paramValue);
        return $result;
    }

I then tried to make a query that would search for movies by title. So if I entered say "Alien" it would return any movies I own with the word "Alien in title. No matter what I have tried I get nothing returned and no errors.

public function getMovieByTitle ($title) {
        $query = "SELECT * FROM movies WHERE title LIKE ?";
        $paramType = "s";
        $paramValue = array(
            $title
        );

        $result = $this->db_handle->runQuery($query, $paramType, $paramValue);
        return $result;
    }

Any points in the right direction is appreciated

I also tried a function to see if title is being passed by $_POST and it shows it is.

2

Answers


  1. Passing a value such as 'Alien' to the LIKE operator does not do what you expect.

    This predicate…

    WHERE title LIKE 'Alien'
    

    … Actually behaves similarly as:

    WHERE title = 'Alien'
    

    If you want to seach for titles that contain a given string, you need to use '%', the wildcard character :

    WHERE title LIKE '%Alien%'
    

    You can either concatenate the percent sign in your code then inject it in the query, or pass the original value to the query and add the wildcard in SQL:

    WHERE title LIKE CONCAT('%', ?, '%')
    
    Login or Signup to reply.
  2. Concatinate % which works as placeholder for an number of characters in sql in the php code

    public function getMovieByTitle ($title) {
            $query = "SELECT * FROM movies WHERE title LIKE ?";
            $paramType = "s";
            $paramValue = array(
              "%".  $title . "%"
            );
    
            $result = $this->db_handle->runQuery($query, $paramType, $paramValue);
            return $result;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search