如何在 HTML 表格中显示带有分隔列的 SQL 查询结果
Posted
技术标签:
【中文标题】如何在 HTML 表格中显示带有分隔列的 SQL 查询结果【英文标题】:How to display SQL query results with columns seperated in HTML table 【发布时间】:2021-04-23 18:40:31 【问题描述】:现在我将 SQL 查询作为“结果”并将所有数据输出为一大块。我通过在 line.innerhtml 行中添加 Category、OEM # 和 Price 将其分开,但我无法弄清楚在 HTML 表中设置它需要做什么,每列分开。这是我现在使用的代码:
<!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>
如您所见,我将所有数据都放入结果中,然后显示在 div id="results" 中。我想要一张桌子,在一个位置有类别,在另一个位置有 oemnumber,在另一个位置有价格。任何关于我将如何去做的建议将不胜感激。谢谢。
编辑:对不起,我忘了添加搜索脚本:
<?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);
【问题讨论】:
【参考方案1】:您可以将您的查询泵入此过程,它会分块出一个呈现的 HTML 表。
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;
【讨论】:
【参考方案2】:我正在尝试做一些我认为会是这样的事情,但我猜我只是没有正确编码:
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);
只是添加表格标签似乎不是正确的方法lol
【讨论】:
以上是关于如何在 HTML 表格中显示带有分隔列的 SQL 查询结果的主要内容,如果未能解决你的问题,请参考以下文章