protected function getCodeFromDatabase()
    {
        $code = '';

        if ($this->use_database == true && $this->pdo_conn) {
            if (Securimage::$_captchaId !== null) {
                $query  = "SELECT * FROM {$this->database_table} WHERE id = ?";
                $stmt   = $this->pdo_conn->prepare($query);
                $result = $stmt->execute(array(Securimage::$_captchaId));
            } else {
                $ip = $_SERVER['REMOTE_ADDR'];
                $ns = $this->namespace;

                // ip is stored in id column when no captchaId
                $query  = "SELECT * FROM {$this->database_table} WHERE id = ? AND namespace = ?";
                $stmt   = $this->pdo_conn->prepare($query);
                $result = $stmt->execute(array($ip, $ns));
            }

            if (!$result) {
                $err = $this->pdo_conn->errorInfo();
                trigger_error("Failed to select code from database.  {$err[0]}: {$err[1]}", E_USER_WARNING);
            } else {
                if ( ($row = $stmt->fetch()) !== false ) {
                    if (false == $this->isCodeExpired($row['created'])) {
                        if ($this->database_driver == self::SI_DRIVER_PGSQL && is_resource($row['audio_data'])) {
                            // pg bytea data returned as stream resource
                            $data = '';
                            while (!feof($row['audio_data'])) {
                                $data .= fgets($row['audio_data']);
                            }
                            $row['audio_data'] = $data;
                        }
                        $code = array(
                            'code'      => $row['code'],
                            'code_disp' => $row['code_display'],
                            'time'      => $row['created'],
                            'audio_data' => $row['audio_data'],
                        );
                    }
                }
            }
        }

        return $code;
    }