'How to display SQL query results with columns seperated in HTML table

Right now I have the SQL query as "results" and just outputting all the data in one big chunk. I separated it some by adding Category, OEM #, and Price into the line.innerHTML line but I cannot figure out what I need to do to set it up in an HTML table with each column separated. Here is the code I am using right now:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="js/jquery-2.2.2.min.js"></script>
<script src="js/bootstrap.min.js"></script>
    <link   href="css/bootstrap.min.css" rel="stylesheet">
    <title>AJAX Search Example</title>
    <script>
    function fetch() {
      // (A) GET SEARCH TERM
 
      var data = new FormData();
      data.append('search', document.getElementById("search").value);
      data.append('ajax', 1);

      // (B) AJAX SEARCH REQUEST
      var xhr = new XMLHttpRequest();
    
      // (CHANGE1) USING ONREADYSTATECHNAGE INSTEAD OF ONLOAD
      
    xhr.onreadystatechange =  function (event) {
        // (CHANGE2) we will check if ajax process has completed or not it goes from 1,2,3,4 means end. 

if(this.readyState == 4){

// (CHANGE2) when ready state comes to 4 we then check what response status was it if it is 200 good else error. 

if(this.status == 200){
    // (CHANGE3) MOVED ALL YOUR CODE HERE 

// (CHANGE4) we need to use responseText instead of response because JSON comes as string that is why we are parsing it to be converted into array

var results = JSON.parse(this.responseText);
    //I have added just a measure to check what the out put is you can remove it latter. open dev console to get the result.
    console.log(results);

wrapper = document.getElementById("results");
    if (results.length > 0) {
          wrapper.innerHTML = "";

// (CHANGE5) UPDATED data ref with results 

for (i = 0; i <  results.length; i++) {
            let line = document.createElement("div");
              //it is just as simple to create id only it must start with alphabet not number 

line.id=`res${[i]}`;

//we created span tag to display price and this is what we will change. on that span we will create a data-price attribute which will hold original price and we will run calculations using that number 

//BIG CHANGE
//BIG CHANGE

//since after parsing individual record will be in Js object so we dont need to access them like array  results[i]['item']

//we access them with dot notation results[i].item

line.innerHTML = `Category:${results[i].category} - OEM #:${results[i].oemnumber} - Price:$<span data-price='${results[i].price}'>${results[i].price}</span>
            select discount >>   
            <a href="#70">%70</a>
    <a href="#60">%60</a>
    <a href="#50">%50</a> <a href="#50">100%</a>`; 
            wrapper.appendChild(line);
          }

 // (CHANGE6) We moved event listeners here so any newly added elements will be updated. 

 //get all the links and apply event listener through loop   
 
    var links = document.querySelectorAll('a');
      

      for ( ii = 0; ii <  links.length; ii++) {
         links[ii].addEventListener("click", function(event) {
         
       //capture link value and get number to be converted to percentage  
       
       var percentage = event.target.innerText.match(/\d+/)[0]/100;
 
 //capture the data-price which is within same div as anchor link
 
 var pricetarget = event.target.parentElement.querySelector('[data-price]');
 
 //get value of data-price
 
 var actualprice=  pricetarget.dataset.price;
 
 //run math and chnage the value on display
 
 pricetarget.innerHTML=(actualprice*percentage).toFixed(2);
      
      
      });
      }

        } else { wrapper.innerHTML = "No results found"; }

 } else {
 
 //if reponse code is other ethan 200 

alert('INTERNET  DEAD OR AJAX FAILED ');

 }

 }
       

            

      };

// (CHANGE7) We moved open event to end so everything is ready before it fires.

xhr.open('POST', "2-search.php");
      xhr.send(data);
      return false;

 
    };
    </script>
  </head>
  <body>
    <!-- (A) SEARCH FORM -->
    <form ID='myForm' onsubmit="return fetch();">
      <h1>SEARCH FOR CATALYTIC CONVERTER</h1>
      <input type="text" id="search" required/>
      <input type="submit" value="Search"/>
    </form>

    <!-- (B) SEARCH RESULTS -->
    <div id="results"></div>


  </body>
  </html>

So as you see I have all the data going to results and then showing in div id="results". I am wanting to have a table and have category in one slot, oemnumber in another, and price in another. Any suggestions on how I would go about doing this would be greatly appreciated. Thank you.

Edit: Sorry I forgot to add the search script:

<?php
// (A) DATABASE CONFIG - CHANGE TO YOUR OWN!
define('DB_HOST', '');
define('DB_NAME', '');
define('DB_CHARSET', '');
define('DB_USER', '');
define('DB_PASSWORD', '');

// (B) CONNECT TO DATABASE
try {
  $pdo = new PDO(
    "mysql:host=".DB_HOST.";charset=".DB_CHARSET.";dbname=".DB_NAME,
    DB_USER, DB_PASSWORD, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]
  );
} catch (Exception $ex) { exit($ex->getMessage()); }

// (C) SEARCH
$stmt = $pdo->prepare("SELECT * FROM `converter_prices` WHERE `category` LIKE ? OR `oemnumber` LIKE ? OR `price`  LIKE ?");
$stmt->execute(["%".$_POST['search']."%", "%".$_POST['search']."%", "%".$_POST['search']."%"]);
$results = $stmt->fetchAll();
if (isset($_POST['ajax'])) { echo json_encode($results); }

I am trying to do something that I assume would be like this, but I am guessing I am just not coding it correctly:

line.innerHTML+= '<tr><td>' + `Category:${results[i].category} + '</td><td>' + OEM #:${results[i].oemnumber} + '</td><td>' + Price:$<span data-price='${results[i].price}'>${results[i].price}</span> + + '</td></tr>'
            select discount >>   
            <a href="#70">%70</a>
    <a href="#60">%60</a>
    <a href="#50">%50</a> <a href="#50">100%</a>`; 
            wrapper.appendChild(line);

Just adding the table tags does not seem to be the right approach lol



Solution 1:[1]

You can pump your query into this procedure and it will chunk out a rendered HTML table.

CREATE PROC dbo.[usp_QueryToHtmlTable]
(
    @Query    NVARCHAR(MAX)                 --A query to turn into HTML format. It should not include an ORDER BY clause.
    ,@OrderBy NVARCHAR(MAX) = NULL          --An optional ORDER BY clause. It should contain the words 'ORDER BY'.
    ,@HTML    NVARCHAR(MAX) = NULL OUTPUT   --The HTML output of the procedure.
)
AS
BEGIN
    SET NOCOUNT ON;

    IF @OrderBy IS NULL BEGIN
SET @OrderBy = '';
    END;

    SET @OrderBy = REPLACE(@OrderBy, '''', '''''');

    DECLARE @realQuery NVARCHAR(MAX) = N'
    DECLARE @headerRow nvarchar(MAX);
    DECLARE @cols nvarchar(MAX);    

    SELECT * INTO #dynSql FROM (' + @Query
                                       + N') sub;

    SELECT @cols = COALESCE(@cols + '', '''''''', '', '''') + ''['' + name + ''] AS ''''td''''''
    FROM tempdb.sys.columns 
    WHERE object_id = object_id(''tempdb..#dynSql'')
    ORDER BY column_id;

    SET @cols = ''SET @HTML = CAST(( SELECT '' + @cols + '' FROM #dynSql ' + @OrderBy
                                       + N' FOR XML PATH(''''tr''''), ELEMENTS XSINIL) AS nvarchar(max))''    

    EXEC sys.sp_executesql @cols, N''@HTML nvarchar(MAX) OUTPUT'', @HTML=@HTML OUTPUT

    SELECT @headerRow = COALESCE(@headerRow + '''', '''') + ''<th>'' + name + ''</th>'' 
    FROM tempdb.sys.columns 
    WHERE object_id = object_id(''tempdb..#dynSql'')
    ORDER BY column_id;

    SET @headerRow = ''<tr>'' + @headerRow + ''</tr>'';

    SET @HTML = ''<table border="1">'' + @headerRow + @HTML + ''</table>'';    
    ';

    EXEC sys.sp_executesql @realQuery
                           ,N'@HTML nvarchar(MAX) OUTPUT'
                           ,@HTML = @HTML OUTPUT;
END;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mike Petri