Search code examples
phphtmlmysqlxampp

How to use an HTML button to trigger a function?


I am populating an HTML table with information from a database and want to trigger it with a button.

Can someone help me with this, and perhaps add some links to relevant website with examples?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div method="GET">
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Nombre</th>
                    <th>Usuario</th>
                </tr>
                <?php
                include "php/populate.php";
                ?>

            </thead>
        </table>
        <input type="button" value="button" id="button">
    </div>
</body>
</html>
<?php 
$result = mysqli_query($enlace,"SELECT * FROM tb_personas");

while($row = mysqli_fetch_array($result))
{
    echo "<tr>";
    echo "<td>" . $row['ID'] . "</td>";
    echo "<td>" . $row['txt_nombre'] . "</td>";
    echo "<td>" . $row['txt_usuario'] . "</td>";
    echo "</tr>";
}
echo "</table>";

mysqli_close($enlace);
?>

Solution

  • You need to use jQuery (the easiest way to use ajax)

    take a look at this question on stackoverflow how to call a php script on a html button click

    additionally you are including your data at table's header, instead they should be included in table's body.

       <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Nombre</th>
                    <th>Usuario</th>
                </tr>                
            </thead>
    
            <tbody>
                <?php   include "php/populate.php";       ?>
            </tbody>
    
    
        </table>