0

I have a php function that dynamically queries a database, and returns 6 tables. I want to store each of these tables as a php array element, pass the array back via JSON/AJAX, and display each table as a seperate on a page. I wrote test code to do all of this. The test code takes an array of HTML strings and passes them back.

The problem I have is that in my test code, I used really simple strings:

$d1 = <<<END

<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>

END; 

$d2 = "<div id='#f-2'>Message 2</div>";

Actually, what I have is a whole bunch of php code to loop through SQL results and construct HTML tables:

while($row=pg_fetch_array($result, null, PGSQL_ASSOC))
  {

    if(!$written_header)
    {
      echo "<table class=\"fancy\" id=\"ticket_list_table\"><thead><tr><th>ID</th><th>Hardware Name</th><th>Serial No.</th><th>IP Address</th><th>Username</th><th>Password</th></tr></thead><tbody>";
      $written_header = true;
    }

    echo "<tr><td>",$row[id],"</td><td>",'$row[hardwarename]',"</td><td>",'$row[serialnumber]',"</td><td>",'$row[ipAddress]',"</td><td>",'$row[username]',"</td><td>",'$row[password]',"</td></tr>";  

  }

  pg_free_result($result);

  if($written_header)
  {
    // close the table body and table object
    echo "</tbody></table>";
  }
  else
  {
    echo "No results.";
  }
  echo "</div>";

How can I store this more complex stuff in a PHP variable so that I can then pass it back as an array element?

hakre
  • 193,403
  • 52
  • 435
  • 836
Damoven
  • 5
  • 1

2 Answers2

0

Not sure if understand you correctly, but

$result = "<table>";
$result .= "<tr>";
$result .= "<trd>";

This .= notation keeps adding new data to the end of previous value.

Anti Veeranna
  • 11,485
  • 4
  • 42
  • 63
  • Yes, you did understand. I basically took out all the echo calls, and built up each block of HTML string by string, via use of .= operator. It works quite well and I can't believe I didn't think if it yesterday. Talk about overthinking a problem. Thanks! Code below: – Damoven Sep 15 '10 at 12:07
0

This is the solution to my own particular problem:

  while($row=pg_fetch_array($result, null, PGSQL_ASSOC))
  {

    if(!$written_header)
    {
      $d1 = "<table class=\"fancy\" id=\"ticket_list_table\"><thead><tr><th>ID</th><th>Hardware Name</th><th>Serial No.</th><th>IP Address</th><th>Username</th><th>Password</th></tr></thead><tbody>";
      $written_header = true;
    }

    $d1 = $d1."<tr><td>$row[id]</td><td>$row[hardwarename]</td><td>$row[serialnumber]</td><td>$row[ipAddress]</td><td>$row[username]</td><td>$row[password]</td></tr>";

  }

  pg_free_result($result);

  if($written_header)
  {
    // close the table body and table object
    $d1 = $d1."</tbody></table>";
  }
  else
  {
    $d1 = $d1."No results.";
  }
Damoven
  • 5
  • 1