Mann
Mann

Reputation: 606

How to add a button after each row of a table from sql?

i have a table with three columns date , title , message.

i will show only date and title in each table and want to add a seperate button after each row then i will show that message .

i have tried

            <?php

        echo "<table style='border: solid 3px aqua;'>";
        echo "<tr><th>Circular/Notice</th><th>DateGenerated</th></tr>";
        class TableRows extends RecursiveIteratorIterator { 
            function __construct($it) { 
                parent::__construct($it, self::LEAVES_ONLY); 
            }
         function current() {
                return "<td style='width:150px;border:1px solid red;'>" . parent::current(). "</td>";
            }

            function beginChildren() { 
                echo "<tr>"; 
            } 

            function endChildren() { 
                echo "</tr>" . "\n";
            } 

        } 

        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "er";

        try {
            $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $stmt = $conn->prepare("SELECT title ,DateGenerated FROM messages"); 
            $stmt->execute();

            // set the resulting array to associative
            $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 
            foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { 
                echo $v;


            }
        }
        catch(PDOException $e) {
            echo "Error: " . $e->getMessage();
        }
        $conn = null;
        echo '<input type ="button" value = "View"/>';
        echo "</table>";

        ?>

and the result am getting is only one button that too at top of the table. enter image description here

Upvotes: 0

Views: 2569

Answers (1)

Dave Houlbrooke
Dave Houlbrooke

Reputation: 428

The <input> needs to be inside a <td>, which needs to be inside a <tr>

Anything inside a HTML table that isn't in a row and cell, gets rendered outside the table.

To have a button for each row, you need to put the code inside your TableRows loop. I would suggest editing the endChildren() function, as follows:

function endChildren() {
    echo '<td><input type="button" value = "View"/></td>';
    echo "</tr>" . "\n";
} 

Upvotes: 2

Related Questions