【问题标题】:TD contenteditable and update value in databaseTD contenteditable 和更新数据库中的值
【发布时间】:2019-06-26 08:14:12
【问题描述】:

我有一个表格,我可以让 td 的内容可编辑,以便用户轻松输入所需的数据。

数据库中的每一行和 td 的值为 null。当用户输入内容时它将具有价值,当单击按钮保存时它将保存/更新

我的 php 为 tbody :

 <?php
$emp_name = $_SESSION["emp_name"];
$month = $_SESSION["month"];
$REMARKS = $_SESSION[""];
$date_now = date('m');
$current_day = date('d');
$sample_var=  $_SESSION["username"] ;

        try {
            $pdo = new PDO('mysql:host=localhost:3306;dbname=******;', '****', '*****' );
            $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
            $stmt = $pdo->prepare(
                " SELECT * from tbl_assessment WHERE employeeName = '{$_SESSION['emp_name']}' "
        );
        $flag = $stmt->execute();
        if ( !$flag ) {
            $info = $stmt->errorInfo();
            exit( $info[2] );
        }
        while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ) {

                @$tbody1 .='<tr>';
                    $tbody1 .=' <input type="hidden" id="id" value="'.$_SESSION['id'].'"/> ';
                    $tbody1 .=' <input type="hidden" id="emp_name" value="'.$_SESSION['emp_name'].'"/> ';
                    $tbody1 .=' <input type="hidden" id="teamCode" value="'.$_SESSION['teamCode'].'"/> ';
                    $tbody1 .=' <input type="hidden" id="sectionCode" value="'.$_SESSION['sectionCode'].'"/> ';


                    $tbody1 .='<td style="height:30px" contenteditable>'.$row["date"].'</td>';
                    $tbody1 .='<td style="height:30px" contenteditable>'.$row["staffName"].'</td>';
                    $tbody1 .='<td style="height:30px" contenteditable>'.$row["findings"].'</td>';
                    $tbody1 .='<td style="height:30px" contenteditable>'.$row["action"].'</td>';
                    $tbody1 .='<td style="height:30px" contenteditable>'.$row["date_accomplished"].'</td>';
                    $tbody1 .='<td><button class="btn btn-warning px-2" id="btnSaveFindings" style="color:black;font-weight:bold;" title="Save"><i class="fas fa-save" aria-hidden="true"></i></button><button class="btn btn-info px-2" id="btnEdit" style="color:black;font-weight:bold;" title="Edit"><i class="fas fa-edit" aria-hidden="true"></i></button></td>';


        @$tbody .='</tr>';
        }   
            }
        catch ( PDOException $e ) {
        echo $e->getMessage();
        $pdo = null;
        }   
?>

我的 html 表格:

<div id="containerDiv" style="background-color:white;border-bottom:3px solid #ff6600;margin-left:50px;margin-right:50px;margin-bottom:140px;" class="animated fadeInUp">
    <div class=""  style="margin-left:15px;margin-right:15px;overflow-x:auto;" ><br>
        <button class="btn btn-default px-3" style="float:right;" id="btnAddRow" name="btnAddRow" title="Add New row"><i class="fas fa-plus" aria-hidden="true"></i></button>
        <table class="assessment" id="assessment" width="1526px" >
        <thead style="background:-moz-linear-gradient( white, gray);">
            <tr>    
                <th colspan="6" style="font-size:20px;">ASSESSMENT/FINDINGS:</th>
            </tr>
            <tr> <!---FIRST TABLE ROW--->
                <th>DATE</th>
                <th>NAME OF THE STAFF/S</th>
                <th>ASSESSMENT/FINDINGS</th>
                <th>ACTION TAKEN</th>
                <th>DATE ACCOMPLISHED</th>
                <th>ACTION</th>
            </tr>
            <tbody>
                <?php echo $tbody1; ?>
            </tbody>
        </thead>
    </table><br><br>
</div>

btnSaveFindings 更新数据库中 td 值的功能是什么?

【问题讨论】:

  • 请我希望有人能帮我解决这个问题..
  • 您可以尝试使用 jquery 和 ajax 来使其正常工作,因为您可以使用 on keyup 之类的事件,或者检查何时按下 enter 键然后运行 ​​ajax 并在那里传递所有这些值,然后执行更新查询.
  • tbl_assessment 表的表结构是什么?
  • 您要究竟做什么?您试图找到问题的答案是什么,您在哪里卡住了?

标签: javascript php sql database contenteditable


【解决方案1】:

有几点需要注意,

  1. 您的查询未使用准备好的语句 - 这对于 PDO 来说非常简单;建议你使用它!
  2. 您的循环可以生成多个具有相同 ID 的 HTML 元素 - 这违反了 ID 的唯一性 - 如果某些内容可以具有相同的 ID,则它可能是一个类。
  3. 打印大块 HTML 时,最好退出 PHP 模式以在需要的地方打印。
  4. 要更新表格,请使用带有 AJAX 的 jQuery - 将类分配给不同的 &lt;td&gt; 元素,以便我们可以使用 jQuery 获取它们,当您单击按钮时,找到该行的最接近的值。向按钮的 data-* 属性添加行唯一标识符,以便我们知道要更新哪一行。
<?php
$emp_name = $_SESSION["emp_name"];
$month = $_SESSION["month"];
$REMARKS = $_SESSION[""];
$date_now = date('m');
$current_day = date('d');
$sample_var = $_SESSION["username"] ;

try {
    $pdo = new PDO('mysql:host=localhost:3306;dbname=******;charset=utf8mb4', '****', '*****' );
    $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

    $stmt = $pdo->prepare("SELECT * FROM tbl_assessment WHERE employeeName = :employeeName");
    $stmt->execute(['employeeName' => $_SESSION['emp_name']]);
    ?>
    <script>
        $(".btnSaveFindings").on("click", function() {
            var id = $(this).data('assessment-id'),
                row = $(this).closest("tr"),
                date = $(row).find('.assessment-date')[0],
                staffname = $(row).find('.assessment-staffname')[0],
                findings = $(row).find('.assessment-findings')[0],
                action = $(row).find('.assessment-action')[0],
                accomplished = $(row).find('.assessment-date-accomplished')[0];

            $.ajax({
                type: "POST",
                url: "updateRow.php",
                data: {id: id,
                           date: date,
                       staffname: staffname,
                       findings: findings,
                       action: action,
                       accomplished: accomplished},
                success: function(data) {
                    var status = data.status,
                        message = data.message;

                   alert(message);
                }
            });
        });
    </script>

    <div id="containerDiv" style="background-color:white;border-bottom:3px solid #ff6600;margin-left:50px;margin-right:50px;margin-bottom:140px;" class="animated fadeInUp">
        <div class=""  style="margin-left:15px;margin-right:15px;overflow-x:auto;" ><br>
            <button class="btn btn-default px-3" style="float:right;" id="btnAddRow" name="btnAddRow" title="Add New row"><i class="fas fa-plus" aria-hidden="true"></i></button>
            <table class="assessment" id="assessment" width="1526px" >
                <thead style="background:-moz-linear-gradient( white, gray);">
                    <tr>    
                        <th colspan="6" style="font-size:20px;">ASSESSMENT/FINDINGS:</th>
                    </tr>
                    <tr> <!---FIRST TABLE ROW--->
                        <th>DATE</th>
                        <th>NAME OF THE STAFF/S</th>
                        <th>ASSESSMENT/FINDINGS</th>
                        <th>ACTION TAKEN</th>
                        <th>DATE ACCOMPLISHED</th>
                        <th>ACTION</th>
                    </tr>
                    <tbody>
                        <?php 
                        while ($row = $stmt->fetch()) { ?>
                            <tr>
                                <td style="height:30px" class="assessment-date" contenteditable><?php echo $row["date"] ?></td>
                                <td style="height:30px" class="assessment-staffname" contenteditable><?php echo $row["staffName"]; ?></td>
                                <td style="height:30px" class="assessment-findings" contenteditable><?php echo $row["findings"]; ?></td>
                                <td style="height:30px" class="assessment-action" contenteditable><?php echo $row["action"]; ?></td>
                                <td style="height:30px" class="assessment-date-accomplished" contenteditable><?php echo $row["date_accomplished"]; ?></td>
                                <td>
                                    <button class="btn btn-warning px-2 btnSaveFindings" style="color:black;font-weight:bold;" title="Save" data-assessment-id="<?php echo $row['id']; ?>">
                                        <i class="fas fa-save" aria-hidden="true"></i>
                                    </button>
                                    <button class="btn btn-info px-2 btnEdit" style="color:black;font-weight:bold;" title="Edit">
                                        <i class="fas fa-edit" aria-hidden="true"></i>
                                    </button>
                                </td>
                            </tr>
                            <?php 
                        }
                        ?>
                    </tbody>
                </thead>
            </table>
            <br />
            <br />
        </div>
    <?php 
} catch(PDOException $e) {
    error_log($e->getMessage());
    echo "An error occurred";
}

然后您需要创建运行查询的文件updateRow.php

<?php
header('Content-Type: application/json');

$pdo = new PDO('mysql:host=localhost:3306;dbname=******;charset=utf8mb4', '****', '*****' );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

// See that the POST is sent
if (empty($_POST)) {
    echo json_encode(['status' = false, 'message' => 'No data was sent. Update aborted']);
    exit;
}

try {
    $stmt = $pdo->prepare("UPDATE tbl_assessment 
                           SET date = :date,
                               staffName = :staffName,
                               findings = :findings,
                               action = :action,
                               date_accomplished = :date_accomplished 
                            WHERE id = :id");
    $stmt->execute(['date' => $_POST['date'],
                    'staffName' => $_POST['staffName'],
                    'findings ' => $_POST['findings'],
                    'action ' => $_POST['action'],
                    'date_accomplished ' => $_POST['date_accomplished'],
                    'id ' => $_POST['id']]);

    echo json_encode(['status' = true, 'message' => 'Update completed.']);
} catch (PDOException $e) {
    error_log($e->getMessage());
    echo json_encode(['status' = false, 'message' => 'An error occurred. Update failed.']);
}

最后一点,在元素上使用 CSS 类而不是内联样式通常会更好。使代码更清晰,代码更可重复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 2016-05-27
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    相关资源
    最近更新 更多