Search code examples
htmlpostgresqlphp-pgsql

How to set a button at the beginning of each line of my table?


I try to have a button at the beginning of each line. I will use this button to open a line on a pop up windows.

I know it is not hard to do but somehow I am struggling to place the button at the beginning of a line.

To give you the context of my code. I generate my table after an SQL query, so I don't know how many lines I will have. Here is the code :

$result = Db::query($requete);

$texte = "<table class='table table-bordered table-sm'><thead>$table_header</thead>";
$texte .= "<tbody>";

if (!pg_num_rows($result)){
    $nb_ligne = "Aucune ligne trouvée !";
}else{
    $nb_ligne ="Nombre de lignes : ".pg_num_rows($result);
}
while($row = pg_fetch_row($result)){
    $texte .= "<tr>";
    foreach ($row as $value){
        $texte .= "<td><button type='button' class='btn btn-primary' onclick=''></button></td><td style='word-break: keep-all'>$value</td>";
    }
    $texte .= "</tr>";
}
$texte .= "</tbody></table>";

$response = new Response();
$response->assign('nb_ligne', 'innerHTML', $nb_ligne);
$response->assign('tableau_resultat', 'innerHTML', $texte);

return $response;

I first create the header of my table. $table_header contains <th> tags and header value. Then I loop on each line of the dataset returned by my query. For each line, I create <tr> tag and for each value I create <td> tag. I use Jaxon (PHP lib to do AJAX) to display my table.

I tried to put a button at the beginning but they are displayed before my table.

I get this ouput : img

The buttons are the blue boxes on the left above headers. I want them to be on the left of each lines apart from header line.

I want to learn from this, so, if possible, explain to me what I'm doing wrong here, or if my approach is lacking insight.


Solution

  • You want the buttons only once per row - why are you creating a button for each column ?!

    while($row = pg_fetch_row($result)){
        $texte .= "<tr><td><button type='button' class='btn btn-primary' onclick=''></button></td>";
        foreach ($row as $value){
            $texte .= "<td style='word-break: keep-all'>$value</td>";
        }
        $texte .= "</tr>";
    }
    

    You should also put an empty cell on the left of your header.