Search code examples
phpmysqlclone

php clone not working how I expected


Trying to construct a simple datagrid from a mySQL db.

The database class I am using to connect returns the result set as an object. I want to clone this object so that i can use the getNext() method to get the headers of the table without moving the pointer forward to drop the first row returned. I expect this to be simple as cloning the result set so that I now have 2 object that are identical. then returning the headers in one object while leaving the other object untouched.

This however has proven to be harder then I thought. Perhaps I am not using clone properly so if you can help please tell me what I am doing wrong.

Below is the code:

        function gethtmlTable($database, $table)
            {
                $db = new DB_Connection();
                $sql = "SELECT * FROM $table;";
                $result = $db->query($sql,$database);
                $tabelheader = clone $result;
                $tablerows = clone $result;
                if (!$result) die($db->getError());
                if ($result->getNumRows() == 0) die('No Results');

                $count = $tabelheader->getNumRows();
                $html = "<table><th>Select</th>";

                // echo "<pre>".var_dump($result)."</pre>";    
                foreach($tabelheader->getNext() as $k => $v){
                       $html .="<th>".$k."</th>";
                }
                while($count > 0){ 
                    $row = $tablerows->getNext();      
                    $html .= "<tr>";
                    $html .= "<td><input type='checkbox' id='checkbox".$count."' name=checkbox".$count." class ='styled' value='checked'></td>";

                    foreach($row as $k => $v){
                            $html .="<td>".$v."</td>";
                    }

                    //foreach($result->getNext() as $k => $v){
                    //   $html .="<td>".$v."</td>";
                    //}
                    $html .="</tr>";
                    $count--;
                 }
                $html .="</table>";
                echo $html;

            }

When I run this function I get back a table with headers and a select box but the first row is always missing. :(


Solution

  • More of a solution than a direct answer, but you don't need to clone your object. Instead, you can change your while loop a bit and just use the $result from your query:

    do
    {
      // do the stuff you are doing now except for fetching a new row
    
    
      // at the end:
      $count--;
      $row = $result->getNext();
    }
    while ($count > 0)