BSWard BSWard - 5 months ago 9
HTML Question

PHP SQL Query - unable to add HTML formatting

I have a database with three tables. A, B and C. Table A has one column: entity_id. Table B has two columns; entity_id, entity_name. Table C has two columns; entity_id, entity_body.

I am trying to use php to create an html table that displays entity_name and entity_body for all entity_id that appear in Table A.

$sql1 = $dbh->prepare('Select B.entity_name, C.entity_body FROM A
INNER JOIN B ON A.entity_id = B.entity_id
INNER JOIN C on A.entity_id = C.entity_id');
$sql1->execute();

while ($row = $sql1->fetchObject()) {
echo '<br><tr><td>';
echo $row->body_value;
echo '</td><td>';
echo $row->title;
echo '</td></tr>';
}


The above query is returning the correct database records: it shows all the relevant rows separated by a line-break.

However, the and HTML tags never seem to be added. The
tags are added. All other tags are recognised and work as expected (e.g. p, div etc.).

Is it possible to format the outputs of a query as a table with HTML tags around the cells and the rows?

Apologies if this is obvious - this is my first attempt at using php with a database. Many thanks,

Ben

Answer

try

  $sql1 = $dbh->prepare('Select B.entity_name, C.entity_body FROM A 
  INNER JOIN B ON A.entity_id = B.entity_id 
  INNER JOIN C on A.entity_id = C.entity_id');
  $sql1->execute();

  echo '<table width="100%">';
  while ($row = $sql1->fetch(PDO::FETCH_OBJ)) {
      echo '<tr>
              <td>';
      echo        $row->entity_body;
      echo ' </td>
             <td>';
      echo        $row->entity_name;
      echo '</td>
           </tr>';
  }
  echo '</table>';