Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums CSS MySQL class – output issues

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #37512
    D3mon
    Member

    Hi guys,

    I’m using a PHP class for my database connections as follows:


    //Query rowset from the database.
    //returns a full row or rows.
    //return value is an associative array with column names as keys.
    public function query($sql) {
    $DBresult = mysql_query($sql);
    if (empty($DBresult)) {
    $DCResults = "";
    return $DCResults;
    } elseif(mysql_num_rows($DBresult) == 1) {
    $DCResults = $this->processRowSet($DBresult, true);
    } else {
    $DCResults = $this->processRowSet($DBresult);
    }
    mysql_free_result($DBresult);
    mysql_close();
    return $DCResults;
    }

    //takes a mysql row set and returns an associative array, where the keys
    //in the array are the column names in the row set. If singleRow is set to
    //true, then it will return a single row instead of an array of rows.
    public function processRowSet($rowSet, $singleRow=false)
    {
    $resultArray = array();
    while($row = mysql_fetch_assoc($rowSet)) {
    array_push($resultArray, $row);
    }
    if($singleRow === true)
    return $resultArray[0];
    return $resultArray;
    }

    If there is one row returned, it returns a simple associative array. In the case of more than one row returned, it returns an array of arrays. This is fine normally, but I’ve run into an issue.

    On queries where I’m not sure how many rows will come back (one or many), I can’t seem to write the loop code that can handle this properly. How can I detect from the resulting array which type it is?

    #100687
    xpy
    Participant

    I believe you should always handle your queries as if they produce more than one rows.
    So you’ll always know that your function returns an array of the results.
    You’ll also know that if your array’s length is 1 you have one result.

    #100688
    D3mon
    Member

    Ah OK. So count($myarray) will return 1 if it’s a single row and > 1 if it’s an array of arrays?

    I guess, since the rest of the site relies on the way this class operates already, I’ll need to check the array length before looping.

    #100699
    D3mon
    Member

    I’m not that hot on OO PHP yet. So, you’re saying this would be better:


    public function processRowSet($rowSet, $singleRow=false)
    {
    $resultArray = array();
    if($singleRow === true)
    return $resultArray[0];
    else
    while($row = mysql_fetch_assoc($rowSet)) {
    array_push($resultArray, $row);
    }
    return $resultArray;
    }
    #100910
    D3mon
    Member

    Thanks guys :D

Viewing 5 posts - 1 through 5 (of 5 total)
  • The forum ‘CSS’ is closed to new topics and replies.