stub function question (simulating data retrieved from a database)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bit Byte

    stub function question (simulating data retrieved from a database)

    PHP noob here (background in C++/C/Java though)

    I want to return dummy data from a stub function, this stub function
    should replicate data from a database. Any idea how I can write this
    stub function?

    i.e. something like this:

    function foo (){

    }


    I want this function to return data that looks like the result of a
    database query - i.e. 0 or more rows, with column headers.

    PS: The format will be fixed i.e. I know exactly the format of the data
    I am expecting (i.e. number of coulmns and column names)

  • petersprc@gmail.com

    #2
    Re: stub function question (simulating data retrieved from a database)

    The structure of the result set depends on the database API used. For
    example, mysql_fetch_arr ay returns an associative array with both
    numeric and string keys.

    Here's an example that works with mysql_fetch_arr ay:

    <?

    function getDataStub()
    {
    $rows = array();
    $rows[] = array('val1-1', 'val1-2', 'val1-3');
    $rows[] = array('val2-1', 'val2-2', 'val2-3');
    $rows[] = array('val3-1', 'val3-2', 'val3-3');

    $cols = array('col1', 'col2', 'col3');
    $items = array();
    foreach ($rows as $row) {
    $item = array();
    for ($i = 0; $i < count($cols); $i++) {
    $item[$i] = $row[$i];
    $item[$cols[$i]] = $row[$i];
    }
    $items[] = $item;
    }
    return $items;
    }

    function getDataMysql()
    {
    $items = array();
    $res = mysql_query("se lect * from t") or die(mysql_error ());
    while ($row = mysql_fetch_arr ay($res)) {
    $items[] = $row;
    }
    return $items;
    }

    function getData()
    {
    return isset($GLOBALS['stubsEnabled']) ? getDataStub() :
    getDataMysql();
    }

    ?>

    Bit Byte wrote:
    PHP noob here (background in C++/C/Java though)
    >
    I want to return dummy data from a stub function, this stub function
    should replicate data from a database. Any idea how I can write this
    stub function?
    >
    i.e. something like this:
    >
    function foo (){
    >
    }
    >
    >
    I want this function to return data that looks like the result of a
    database query - i.e. 0 or more rows, with column headers.
    >
    PS: The format will be fixed i.e. I know exactly the format of the data
    I am expecting (i.e. number of coulmns and column names)

    Comment

    Working...