How to Insert a Checkbox in PHP MySQL

Save

PHP can select records from a MySQL database, and then provide a way to choose selected records using an HTML check box. Check boxes can also be used to selectively delete or amend records. The relevant data can then be updated subject to the selections made on a Web page. Check boxes provide an easy way for users to interact with the data and select only the records she needs to update. PHP will then perform the relevant actions.

  • Connect to the selected database like so:

    <?php

    $hostname="localhost"; // Host name

    $user=""; // Mysql username

    $pass=""; // Mysql password

    $database_name="sales"; // Database name

    $table_name="saleshistory"; // Table name

    // Connect to server and select the database as required:

    mysql_connect("$hostname", "$user", "$pass") or die ("cannot connect to sales");

    mysql_select_db("$database_name") or die ("cannot select the database");

  • Select records from the table as required:

    $salessql="SELECT * FROM $table_name";

    $salesresult=mysql_query($salessql);

    $count=mysql_num_rows($salesresult);

  • Obtain the records selected with a while statement:

    while($rows=mysql_fetch_array($salesresult))

    ?>

    The end of the first PHP section is marked with ?> above.

  • Use HTML and PHP to output the details of the check box

    information as follows:

    <table>

    <tr>

    <td align="center" ><input name="checkbox[]" type="checkbox" salesid="checkbox[]" value="<? echo $rows['salesid']; ?>"></td>

    <td ><? echo $rows['salesid']; ?></td>

    <td ><? echo $rows['customerfirstname']; ?></td>

    <td ><? echo $rows['customerlastname']; ?></td>

    <td ><? echo $rows['customeremail']; ?></td>

    </tr>

    </table>

    The checkbox is indicated by the "salesid" field in each record. For each salesid displayed on the screen, the user can select or ignore the record. The Sales identifier number (salesid) will be checked or unchecked and indicates to PHP that this record should be updated. The other fields in the list provide additional information.

Tips & Warnings

  • Although a while statement was provided as an example of populating a check box in this instance, it can also be implemented by line by line commands in an HTML form without a while loop.

References

  • Photo Credit Jupiterimages/Creatas/Getty Images
Promoted By Zergnet

Comments

You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!