繁体   English   中英

使用JavaScript的PHP和HTML表搜索

[英]PHP and HTML table search using javascript

我想创建一个搜索框,当键入搜索短语时,它仅显示匹配的条目; 功能与此处所述相同:

如何在HTML表格上执行实时搜索和过滤

区别在于,我拥有的表是根据PHP循环和SQL数据创建的。 但是,我不确定如何采用该代码为我工作。

我个人认为,这可能与“ //打印表行”部分有关。

这是代码:

 var $search_rows = $('#table tr'); $('#search').keyup(function() { var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase(); $search_rows.show().filter(function() { var text = $(this).text().replace(/\\s+/g, ' ').toLowerCase(); return !~text.indexOf(val); }).hide(); }); 
 <html> <script src="./jquery-1.6.4.js"></script> <script src="./sorttable.js"></script> <script src="./searchbox.js"></script> <link rel="stylesheet" href="styles.css"> <head> <title>Tau Empire Cadre Census</title> </head> <body> <?php //// //// //// //// // DATABASE //// //// //// //// //database credentials $db_host="localhost"; $db_user="tau"; $db_pwd="kuhohNg3"; $db="tau_census"; $db_table="cadres"; //make the connection if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($db)) die("Can't select database"); // sending query $result = mysql_query("SELECT * FROM {$db_table}"); if (!$result) { die("Query to show fields from table failed"); } //assign a variable the number of returned table fields $fields_num = mysql_num_fields($result); //// //// //// //// // HEADING //// //// //// //// echo "<h1>Tau Empire Cadre Census</h1>"; // Search box echo '<input type="text" id="search" placeholder="Type to search">'; //// //// //// //// // TABLE //// //// //// //// //create the table, and use the JS sortable script echo '<table id="table" class="sortable"><tr>'; // printing table headers echo "<td class=headings>Designation</td>"; echo "<td class=headings>Location</td>"; echo "<td class=headings>Founding</td>"; echo "<td class=headings>Commanding Officer</td>"; echo "<td class=headings>Current Status</td>"; echo "<td class=headings>Current Location</td>"; echo "<td class=headings>Mission</td>"; echo "</tr>\\n"; // printing table rows while($row = mysql_fetch_row($result)) { echo "<tr>"; // For each field print the content for($i=1; $i<$fields_num; $i++) { echo "<td>" . $row[$i] . "</td>"; } echo "</tr>"; } echo "</table>"; mysql_free_result($result); ?> </body> </html> 

运行此命令不会引发任何错误,但也不会起作用。 这需要比我更大的大脑来锻炼。

我现在正在努力,谢谢大家的协助。 这可能是以下各项的组合:

i)正确插入以下脚本行:

<script src="./jquery.min.js"></script>
<script src="./jquery-1.6.4.js"></script>

ii)将外部JS包装在$(function(){...});

iii)错误地构造了我的表行和数据字段。

由于您认为问题出在“打印表行”部分,因此我会指出您确实在该部分中存在格式问题,请像这样解决它们,它可能会解决一些问题:

// printing table rows
while($row = mysql_fetch_row($result))
{
    echo "<tr>";
    // For each field print the content
    for($i=1; $i<$fields_num; $i++) {
        echo "<td>" . $row[$i] . "</td>";
    }
    echo "</tr>";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM