Search code examples
phpmysqlfunctionpdophpstorm

"PDO method not found" inside PHP Function (PhpStorm)


I wrote a function in php that counts the amount of rows in a MySQL database, called count_series(). This function works fine, however, PhpStorm gives me a 'method not found' error for the following the following functions: prepare(), execute(), rowCount().

Does anyone know what the cause of this may be?

/**
 * Connects to the database
 * @param $host
 * @param $db
 * @param $user
 * @param $pass
 * @return PDO
 */
function connect_db($host, $db, $user, $pass) {
    $charset = 'utf8mb4';

    $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
    $options = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ];
    try {
        $pdo = new PDO($dsn, $user, $pass, $options);
    } catch (\PDOException $e) {
        echo sprintf("Failed to connect. %s",$e->getMessage());
    }
    return $pdo;
}


/**
 * Returns the amount of series in the database
 * @param $db
 * @return mixed
 */
function count_series($db) {
    $stmt = $db->prepare('SELECT COUNT(id) FROM ddwt18_week1.series');
    $stmt->execute();
    $count = $stmt->rowCount();
    return $count;
}

Solution

  • You're omitting type hinting everywhere so PhpStorm (or even a human being) has no way to figure out by itself. Instead of this:

    function count_series($db) {
    }
    

    ... I'd expect to see something like:

    function count_series(PDO $db): int {
    }
    

    ... or at least this (if you need to support earlier PHP versions)

    function count_series(PDO $db) {
    }
    

    Please replace PDO with the actual class name if it isn't that one.

    Same for dobclocks (though they're actually redundant when it comes to code instellisense if the code is self-documenting). Instead of this:

     * @param $db
     * @return mixed
    

    ... use this:

     * @param PDO $db
     * @return int