我正在尝试创建一个从 SQL 数据库中提取数据的表,表中的每一行都是一个指向其相应页面的可点击链接,具体取决于数据库中的第一列数据。
我已经成功地分别完成了这两个部分,即创建一个包含 SQL 数据的表,并且我已经成功地创建了一个每行都有一个可点击链接的表,但是我正在努力将两者结合起来。
我正在使用 .js 来监听点击并根据“tr data-href='url'”将您发送出去。
用于创建表格 SQL 数据的 php 脚本首先创建“tr”,然后用每个单元格填充该行,关闭“/tr”并对所有行重复。
如何让 php 写入“tr data-href='url'”,其中“url”与每行数据的第一列相同?
我的PHP脚本如下,后面是五行JS。
<?php
$host = "localhost";
$user = "user";
$pass = "pass";
$db_name = "FFD";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT id,name,location,plots,blurb FROM Sites");
$all_property = array(); //declare an array for saving property
//showing property
echo '
<div class="content-container">
<h1>Table heading</h1>
<section>
<div class="tbl-header">
<table cellpadding="0" cellspacing="0" border="0">
<thead>
<tr>'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<th>' . $property->name . '</th>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>
</thead>
</table>
</div>
<div class="tbl-content">
<table cellpadding="0" cellspacing="0" border="0">
<tbody>';
//end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo '</tbody></table></div></section></div>';
?>
$(document).ready(function(){
$('tr[data-href]').on("click", function() {
document.location = $(this).data('href');
});
});
我可能只是太厚,错过了一些简单而明显的东西。
提前致谢!
最佳答案
您可以像这样连接您的网址(假设 id
是带有网址的列)
while ($row = mysqli_fetch_array($result)) {
echo '<tr data-href="' . $row['id'] . '">';
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>';
}
echo '</tr>';
}
关于javascript - 如何使用从 SQL 数据库请求的相同数据在 <tr> 中创建链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57875659/