Change Table Row Background Color When Qty Below 10 Using PHP/MySQL
Submitted by argie on Monday, March 24, 2014 - 12:45.
This tutorial will teach you on how to change table row background color when the qty is bellow 10. I use 10 as a default minimum value of qty, you can change it to any number if you want. This tutorial is helpful for thus creating a system that involves products. This is useful because it provides a legend or a prom the certain product is bellow the minimum qty. The admin can easily identify which product need to be order by the use of this feature. Follow the guidelines bellow on how to this feature.
This is the part of the code above that trigger to change the bgcolor to red if the qty is bellow 10.
Make sure that you follow properly all the instruction above to run this feature. Hope this code will help you in your project.
Creating Our Database
First we are going to create our database which stores our data. To create a database: 1. Open phpmyadmin 2. Then create database and name it as "tutorial". 3. After creating a database name, click the SQL and paste the following code.- CREATE TABLE IF NOT EXISTS `products` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `name` varchar(200) NOT NULL,
- `price` int(11) NOT NULL,
- `qty` int(11) NOT NULL,
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
Creating our Database Connection
Next step is to create a database connection and save it as "connect.php". In this Step, we will write our connection script in PDO format.- <?php
- /* Database config */
- $db_host = 'localhost';
- $db_user = 'root';
- $db_pass = '';
- $db_database = 'tutorial';
- /* End config */
- $db = new PDO('mysql:host='.$db_host.';dbname='.$db_database, $db_user, $db_pass);
- $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- ?>
Creating Our Display
The code bellow will give us the idea on how to change the bgcolor when the qty is bellow 10. I use if else statement to change the bgcolor. Copy the code bellow and save it as "index.php".- <table id="resultTable" data-responsive="table" style="text-align: left; width: 400px;" border="1" cellspacing="0" cellpadding="4">
- <thead>
- <tr>
- <th> Name </th>
- <th> Price </th>
- <th> Quantity </th>
- </tr>
- </thead>
- <tbody>
- <?php
- include('connect.php');
- $result = $db->prepare("SELECT * FROM products");
- $result->execute();
- for($i=0; $row = $result->fetch(); $i++){
- $availableqty=$row['qty'];
- if ($availableqty < 10) {
- echo '<tr class="record" bgcolor="red" style="color: white;">';
- }
- else {
- echo '<tr class="record">';
- }
- ?>
- <td><?php echo $row['name']; ?></td>
- <td><?php echo $row['price']; ?></td>
- <td><?php echo $row['qty']; ?></td>
- </tr>
- <?php
- }
- ?>
- </tbody>
- </table>
- $availableqty=$row['qty'];
- if ($availableqty < 10) {
- echo '<tr class="record" bgcolor="red" style="color: white;">';
- }
- else {
- echo '<tr class="record">';
- }
Add new comment
- 1613 views