marked-down
marked-down

Reputation: 10408

PDOStatement::fetchAll() expects parameter 1 to be long, string given?

I have a basic database handler class where I have a public method that returns a result set using the PDO::FETCH_ASSOC argument:

public function resultSet() {
    $this->execute();
    return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}

However, I have determined that I need to use PDO::FETCH_COLUMN for a few usage cases, and so to maintain backwards compatibility, I added an optional parameter to my method:

public function resultSet($fetchType = "PDO::FETCH_ASSOC") {
    $this->execute();
    return $this->stmt->fetchAll($fetchType);
}

This results in an error instead of my expected return:

Warning: PDOStatement::fetchAll() expects parameter 1 to be long, string given

I understand that I am passing it a string, since I defined $fetchType as a string, but I don't know what long is at all, or how to define an optional parameter that contains my preferred fetch mode.

I decide to look at the documentation for PDO::fetchAll() and I only get more confused... the first data type it is expecting is an integer? (int $fetch_type).

So:

  1. How can I define an optional parameter which accepts a fetch type and passes it correctly? and

  2. Why is the first accepted parameter of the data type integer?

Upvotes: 2

Views: 4977

Answers (1)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

the warning explains it all, just change it to like:

public function resultSet($fetchType = PDO::FETCH_ASSOC) {
    $this->execute();
    return $this->stmt->fetchAll($fetchType);
}

Upvotes: 3

Related Questions