user1667630
user1667630

Reputation: 297

checkbox in a table in php

I have table which will be populated (from reading from mysql table). I should provide the user an option to select a row and delete it from the database. Till now I have populated the table (by reading from the mysql). But I dont know how to add a checkbox to each row. This is what I have till now.

<html>
<body>
<?php
    $username="root";
    $password="root";
    $database="test";

    mysql_connect(localhost,$username,$password);
    @mysql_select_db($database) or die( "Unable to select database");

    $query="SELECT * FROM table1";
    $result=mysql_query($query);
    $num=mysql_numrows($result);
    mysql_close();
?>

<?php
    $i=0;
    echo "<table width='600' cellpadding='5' cellspacing='5' border='1'>";
    while ($i < $num) {
        $f1=mysql_result($result,$i,"sno");
        $f2=mysql_result($result,$i,"lastname");
        $f3=mysql_result($result,$i,"firstname");
?>

<font face="Arial, Helvetica, sans-serif"><?php echo "<tr><td> $f1 </td><td>$f2 </td>
<td> $f3 </td></tr>"; ?></font>

<?php
        $i++;
    }
    echo "</table>";
?>
</body>
</html>

Can anyone please help me how to add a checkbox to each row.

Thanks

Upvotes: 1

Views: 9888

Answers (2)

Moch. Rasyid
Moch. Rasyid

Reputation: 356

Sadly, i still cannot comment on answers. But i want to improve Max answered code.

I would use this instead :

<?php echo "<tr><td> $f1 </td><td>$f2 </td>
<td> $f3 </td><td></td><td><input type=\"checkbox\" name=\"checkbox[$f1]\" value=\"\" id=\"checkbox\"></td></tr>"; ?>

please note that i add '$f1' variable after 'checkbox' on name variable, so you can post checked row all at once. You can change '$f1' variable into some unique value that suit your needs. I think you'll need it since you want to add checkbox on your data rows. ;)

Upvotes: 1

Maxi
Maxi

Reputation: 743

Just add the HTML code for rendering a checkbox in your php code e.g

<?php echo "<tr><td> $f1 </td><td>$f2 </td>
    <td> $f3 </td><td></td><td><input type=\"checkbox\" name=\"checkbox\" value=\"\" id=\"checkbox\"></td></tr>"; ?>

Note the backslashes before the double quotes.

Upvotes: 4

Related Questions