dongsang6899 2019-06-26 08:14
浏览 73

TD在数据库中具有可信度和更新价值

I have a table which i make the td's contenteditable, for the user to easily input the data needed.

Every rows and td have value of null in database. It will have value when the user will input something and it will save/update when button save is click

my php for 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;
        }   
?>

my html for table :

<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>

what would be the function of btnSaveFindings to update the value of td in database?

  • 写回答

1条回答 默认 最新

  • duanliang789262 2019-07-02 12:23
    关注

    A few things to note,

    1. Your query is not using a prepared statement - which is very simple with PDO; suggest you use that!
    2. Your loop can generate multiple HTML elements with the same ID - this violates the uniqueness of an ID - if something can have the same ID, it can probably be a class instead.
    3. When printing large blocks of HTML, its often better to exit PHP mode to print it where you need it.
    4. To update the table, use jQuery with AJAX - assign classes to the different <td> elements, so we can fetch them with jQuery, and when you click the button, find the closest values of that row. Add a rows unique identifier to a data-* attribute of the button, so we know which row to update.
    <?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";
    }
    

    Then you need to create the file updateRow.php that runs the query.

    <?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.']);
    }
    

    As a final note, its often way better to use CSS classes on elements instead of inline styling. Makes for cleaner code, and more repeatable code.

    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)