0
public function getStudent($id){
    $sth = $this->con->prepare("SELECT * FROM students WHERE id=:id");
    $sth->bindParam("id", $id, PDO::PARAM_INT);
    $sth->execute();
    $student = $sth->fetchObject();
    return $student;
}

(1) http://localhost/slim-framework/public/api/v1/student/1

(2) http://localhost/slim-framework/public/api/v1/student/1fgff

With 'GET' request using the code above, URL 1 and 2 above gave me the same result which suppose not to be.

Please, any help on how I can make URL 2 to flag error since it is not an integer?

phaheez
  • 1
  • 3
  • This obviously has nothing with PDO but with validating input data. – u_mulder Jun 02 '18 at 20:29
  • cuz `(int) '1' === 1` and `(int) '1fgff' === 1`. The best way to handle that is check if `$id` is numeric or not, and raise an error in that case. – Federkun Jun 02 '18 at 20:31
  • When you do `PDO::PARAM_INT` this casts the variable to an integer. Remove that and your code should fail as expected. – Mike Jun 02 '18 at 20:38
  • Actually, I started to do a bit of research and it turns out I was wrong. `PDO::PARAM_INT` will cast it to a float, not integer. See my answer [here](https://stackoverflow.com/questions/16881085/why-do-we-need-to-specify-the-parameter-type-in-bindparam/50662065#50662065). – Mike Jun 03 '18 at 00:46

2 Answers2

0

Hi I hope this will help you

In your case it will be

public function getStudent(int $id){
 .......
}

If the id comes something else instead of int you will get php error

http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

Aram Grigoryan
  • 740
  • 1
  • 6
  • 24
0
public function getStudent($id){
    if(is_numeric($id)) {
        $sth = $this->con->prepare("SELECT * FROM students WHERE id=:id");
        $sth->bindParam("id", $id);
        $sth->execute();
        $sth->fetchObject();
        return true;
    }else {
        return false;
    }
}

I got it working now by following @u_mulder and @Federkun suggestion by using the is_numeric() method to check if the id is an integer or not.

Thanks everyone for your effort.

phaheez
  • 1
  • 3