如何使用所选行的数据

How to use the data from the row selected?

本文关键字:数据 何使用      更新时间:2023-09-26

如何从我选择的表中收集行数据并在结果中使用它?

这是我用来显示数据输入屏幕的javascript,一旦通过选择行调用了函数。现在我只需要在PHP中设计一个表单,它将包括(1)所选行中的一些数据和(2)将收集的一些新数据。

下面是选择行并调用数据输入表单的Javascript
$(document).ready(function () {
    $("tr").live('click',function(){
        $.post('data_entry_form.php', function(data) {
            $('#section2').html(data);
        });
    });
});
下面是PHP脚本
<?php
require_once "config.php";
$dbh = new PDO($dsn, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$result = $dbh->query("SELECT aif_id, fee_source_id, company_name_per_sedar, document_filing_date FROM a_aif ORDER BY aif_id DESC");
$result->setFetchMode(PDO::FETCH_ASSOC);
echo "<table id='"all_aifs'">";
echo "<tr>";
echo "<th><b>Document ID</b></th>";
echo "<th><b>Pubco Name</b></th>";
echo "<th><b>Filing Date</b></th>";
echo "<th><b>PDF</b></th>";
echo "</tr>";
foreach($result as $index => $row) {
echo "<tr>";
echo "<td>$row[fee_source_id]</td>";
echo "<td>$row[company_name_per_sedar]</td>";
echo "<td>$row[document_filing_date]</td>";
echo "<td>Placeholder</td>";
echo "</tr>";
}
echo "</table>";
echo "<br>";
$dbh = NULL;
?>

这个问题的"正确"答案是不从DOM读取。这不是个好主意。我建议您将记录id传递给ajax调用,并让ajax调用返回一个已经填充的表单。

//PHP
//place the data attribute in the tr
echo "<tr data-recordId='".$row['id']."'>";

//JS
$(document).ready(function () {
    $("tr").live('click',function(){
        //Get the ID from the row clicked
        var id = $(this).data('recordId'); 
        //short-hand
        $('#section2').load('data_entry_form.php?id='+id);
    });
});

然后您的ajax页面将读取$_REQUEST['id']以获得正在编辑的表单的id。

//Ajax side PHP
$id = (int)$_REQUEST['id'];
//Fetch data and use it to pre-populate form item

你可以像这样预先填充你的输入

<input type="text" value="<?php  echo $row['value']; ?>" />

echo '<input type="text" value="'.$row['value'].'" />';

注意:如果您的值包含引号,您将需要用代码&quot;

替换它们
echo '<input type="text" value="'.str_replace('"', '&quot;', $row['value']).'" />';

在事件处理程序中,this和$(this)指向您选择的行:

$("tr").live('click',function(){
    // this.cells[1] is the cell that contains Pubco Name
    // You can also use $(this).children("td")[1]
    ...
});