Ibn Saeed
Ibn Saeed

Reputation: 3301

Can anyone explain the following PHP Code?

Can anyone explain what the following PHP Code does


function query($query_string) 
    {
        if ($query_string == "") {
            return 0;
        }

        if (!$this->connect()) {
            return 0; 
        };

        if ($this->QueryID) {
            $this->free_result();
        }

        if ($this->RecordsPerPage && $this->PageNumber) {
            $query_string .= " LIMIT " . (($this->PageNumber - 1) * $this->RecordsPerPage) . ", " . $this->RecordsPerPage;
            $this->RecordsPerPage = 0;
            $this->PageNumber = 0;
        } else if ($this->RecordsPerPage) {
            $query_string .= " LIMIT " . $this->Offset . ", " . $this->RecordsPerPage;
            $this->Offset = 0;
            $this->RecordsPerPage = 0;
        }

        $this->QueryID = @mysql_query($query_string, $this->LinkID);
        $this->Row   = 0;
        $this->Errno = mysql_errno();
        $this->Error = mysql_error();
        if (!$this->QueryID) {
            $this->halt("Invalid SQL: " . $query_string);
        }

        return $this->QueryID;
    }

function next_record() 
    {
        if (!$this->QueryID) {
            $this->halt("next_record called with no query pending.");
            return 0;
        }

        $this->Record = @mysql_fetch_array($this->QueryID);
        $this->Row   += 1;
        $this->Errno  = mysql_errno();
        $this->Error  = mysql_error();

        $stat = is_array($this->Record);
        if (!$stat && $this->AutoFree) {
            $this->free_result();
        }
        return $stat;
    }

Can the above be done in a simpler way , would it be wise to use an ORM ?

Upvotes: 0

Views: 238

Answers (2)

Ross
Ross

Reputation: 46987

The first class method looks like it performs a MySQL query and adds a LIMIT clause for pagination. The second moves the current query onto the next record, while incrementing the pagination counters.

In more detail, here's the first sample:

  • Exit the method if the query is empty or the database connection doesn't exist.
  • Free any existing query.
  • If the number of records per page and page number are set:
    • Add them to the LIMIT clause of the query.
    • And reset them to 0.
  • Otherwise if records per page is set:
    • Add it to the LIMIT clause of the query.
    • And reset them to 0.
  • Run the query.
  • Set the current row to 0.
  • Collect errors.
  • If the query failed halt with the error.
  • Return the query.

And the second:

  • If the query is not set halt with an error.
  • Fetch row information as an array for the current row.
  • Increment the row number.
  • Catch any errors.
  • If the result isn't an array free/close the query.
  • Otherwise return the result set.

Upvotes: 5

Vijay Kumbhar
Vijay Kumbhar

Reputation:

Yes you are right Ross it something like pagination function in a class which calls the records one by one.

Upvotes: 0

Related Questions