PHP script that dynamically highlights text based on values retrieved from a database

I have multiple small HTML tables generated by PHP on a single page, each with a unique <table id="">. The data in these tables corresponds to entries in a MySQL table with matching IDs.

What I am looking for is to automatically highlight the values in each HTML table that match the data in the corresponding row of the MySQL table with the same ID.

Instead of using checkboxes and manual selection, I need this highlighting process to happen seamlessly without any user interaction. Typically, with checkboxes, the functionality would resemble something like this: https://jsfiddle.net/zt54jqtL/ Thanks!!

<div>

<form id="form1" name="form1" method="post" action="">
    <label>
        <input type="checkbox" name="SelectAll" class="all" />All</label>
    <label>
        <input type="checkbox" name="2" class="selector" />2</label>
    <label>
        <input type="checkbox" name="7" class="selector" />7</label>
    <label>
        <input type="checkbox" name="7" class="selector" />7</label>

</form>

PHP code:

 <?php

$conn=mysqli_connect("localhost","root","","Mdata");

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }


function print_tableX ($conn, $id) {
    $sql = "SELECT Value1, Value2, Value3, Value4, Value5, Value6, Value7, Value8 FROM tableA";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        echo "<table id='$id'>";
        while($row = $result->fetch_assoc()) {
            echo '<tr><td>' . join('</td><td>', $row) . "</td></tr>\n" ;
        }
        echo "</table>";
    }
}  


$result = $conn->query("SELECT sID from tableB");
while ($row = $result->fetch_assoc()) {
    print_tableX ($conn, $row['sID']);
}

?>

Answer №1

It seems like there may be some confusion regarding the question. Additionally, it is not clear from the provided code which rows need to be highlighted.

Let me illustrate the HTML that is generated:

<table id="tab1">
    <tr data-dbval="3"><td>Value</td><td>3</td></tr>
    <tr data-dbval="5"><td>Value</td><td>5</td></tr>
    <tr data-dbval="8"><td>Value</td><td>8</td></tr>
 </table>

 <table id="tab2">
    <tr data-dbval="2"><td>Value</td><td>2</td></tr>
    <tr data-dbval="7"><td>Value</td><td>7</td></tr>
    <tr data-dbval="8"><td>Value</td><td>8</td></tr>
 </table>

Furthermore, here is a JavaScript object with references to the rows that require highlighting:

<script>
    var defaultValue={"tab1":["3","8"],"tab2":["7"]}
</script>

The jQuery code below fetches the values to be highlighted for each table and adds a "highlight" class to the tr element:

$(document).ready(function() {

  $.each(defaultValue,function(k,v){
    var $tab=$("table#"+k);
    if($tab.length>0){
        $.each(v,function(k1,v1){
        $tab.find("tr[data-dbval='"+v1+"']").addClass("highlight");
      })
    }
  })

});

https://jsfiddle.net/moc5sq4w/

If you want to generate a JavaScript object from PHP, you can use the following method (please note, this includes embedded PHP which may not be ideal):

<script>
var defaultValue=<?php
$result = $conn->query("SELECT sID from tableB");
$out=array();
while ($row = $result->fetch_assoc()) {
    $id=$row['sID'];
    $out[$id]=array();
    $sql = "SELECT Value1, Value2, Value3, Value4, Value5 FROM tableA WHERE sID='$id'";
    $result1 = $conn->query($sql);
    if ($result1->num_rows > 0) {
        while($row1 = $result1->fetch_assoc()) {
           $out[$id][]=$row;
        }
    }
}
echo json_encode($out);

?>;</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When hovering over the mouse on a button, a card shadow effect will appear

Hi there! I've implemented a hover effect on a card in my code. When the user hovers over the card, a shadow effect and an Add To Cart button will appear. However, I want to display the card shadow effect when the user hovers over the button as well. ...

The ThreeJS WebGLRenderTarget is displaying an empty texture

Utilizing A-Frame and Three.JS, my goal is to render to a WebGLRenderTarget and generate a material based on its texture. Here's a snippet of the code: var targetPlane = new THREE.Mesh( new THREE.PlaneBufferGeometry(2, 2), new THREE.MeshBasicMate ...

What is the best way to display Bootstrap dynamic tabs in a single row without them overflowing and requiring a scroll button to access all the tabs

Is there a way to dynamically display Bootstrap tabs? I want the content in the tab to show when the link is clicked, and also have a close button. I need the tabs to be aligned in a single row without wrapping down if they don't fit. Here's an ...

What is the best way to showcase an endless amount of items in a

I'm facing an issue with the layout of items in my view. I have a list of items, and I can display up to 6 items at a time using class="col-md-2". However, when there are more than 6 items, they move to the next row automatically. I want them to be d ...

Issues arise when attempting to use the Android KeyUp, KeyDown, and KeyPress events in conjunction with Angular2

I am encountering an issue where I consistently receive a keyCode of 229 in Android Chrome browsers when running either: <input type="text" (keydown)="testKeyCodes($event)"/> <!-- or --> <input type="text" (keyup)="testKeyCodes($event)"/& ...

Embed a subcomponent within another component triggered by an onClick event in ReactJS

Watch this quick demo to see my project in action. So, here's the deal - I have a menu with different options, and when "Tickers" is selected, I want it to display the Tabs component. However, if any other menu option is chosen, I don't want the ...

I am having trouble retrieving images from the backend API. Can someone assist me in resolving this issue?

I am facing an issue while trying to upload an image along with its details. I am able to retrieve all the information but the image is not displaying in the browser. My backend API is built using PHP Laravel and the images are stored in the Storage/app/ap ...

There appears to be an issue with Mongoose Unique not functioning properly, as it is allowing

Below is the complete code snippet I am using to validate user data: import { Schema, model } from 'mongoose'; import { User } from './user.interface'; const userSchema = new Schema<User>({ id: { type: Number, required: ...

The ReplaceWith method fails to function properly when used in conjunction with the

As someone who is new to JQuery, I am currently experimenting with ReplaceWith and Clone methods in order to revert the data in text boxes back to their original state when a user clicks a Cancel button. The idea is that when the user clicks Edit, the Edit ...

Creating Ajax form partials in Rails for multiple models allows for more dynamic and efficient

Having this AJAX code snippet (sourced from: ), which is used across various views like new.html.erb and edit.html.erb, I am looking to avoid redundancy by utilizing partials: app/views/cities/_state_city_form.html.erb <p> State: <%= select(:s ...

NextAuth credentials are undefined and authentication is malfunctioning in React

I encountered the following issue: https://i.sstatic.net/3VBoJ.png This is the code snippet that I am using: return ( <> {Object.values(providers).map((provider) => { if (provider.id === "credentials") { ret ...

Encountering unresponsive npm behavior post-prefix modification

Recently, I attempted to update my IONIC CLI via npm. The installation was successful multiple times, but the version of CLI remained unchanged. After some research, I decided to modify the npm prefix, which resulted in the IONIC command not being found. F ...

Load Bootstrap and Popper using Require.js and CDN

My goal is to utilize require.js to load bootstrap and jquery from a CDN. Although similar questions have been asked previously (such as Steve Eynon's response in Issue Loading PopperJS and Bootstrap via RequireJS, Even After Using Recommended Popper ...

Utilize a for loop within a query to showcase a modal popup

I have a specific requirement: I want to display a modal popup window based on a for loop using jQuery. I have attempted the following approach, where I want the modal popup to be displayed based on the value of a flag. For example, if the Flag value is 3, ...

Creating a custom loading page in Next.js 13: A step-by-step guide

Hello, I am currently working on implementing a loading page for my website to enhance the user experience during a longer loading time. I have created a simple functional component that displays a loading message and imported it into my layout.jsx file in ...

Cancel a batch upload request using AJAX

Currently, I am working on implementing a feature for aborting a multiple file upload process while also displaying the progress of the upload with a progress bar. My objective is to ensure that when the user clicks on the abort button, not only does the ...

When the screen size changes, the centrally aligned position of sticky elements does not stay consistent

It has come to my attention that when centrally aligning an element with position sticky, the alignment can start to malfunction upon reducing the screen width past a certain point, depending on the width of the element. Unlike position: fixed, the sticky ...

Selecting elements with jQuery allows you to manipulate the

Encountering issues with jQuery selectors. This is how my HTML looks: <form method="" action=""> <p id="question_1"> <h1 id="question">1. A Question</h1> <div id="choices"> ...

Having difficulty aligning Bootstrap elements with my custom CSS

My attempt to align my search bar with the "Art Store" text on the same vertical level has been unsuccessful so far. <div id="logoRow" > <h1>Art Store</h1> <form class="searchBar"> ...

"Resetting the state of a form in AngularJS2: A step-by

Looking to reset the form state from dirty/touched in angular? I am currently delving into the world of angular2 and working on a form with validation. In my journey, I came across this code snippet: <form *ngIf="booleanFlag">..</form> This ...