简体   繁体   中英

How to view/edit/delete records from a checklist table in php/mysql

I've built a checklist table in php, the data gets saved in a mysql database table.

With the below code, the data gets saved in the database, now I want to be able to edit and delete the records. The database table has two columns - auto-increment Id and ColRow which has the values of the checked boxes. The values are fetched from the different tables of the database. The header and the first columns are fetched from two tables which gets saved in the report table depending on the boxes being checked by the user.

Here's the code:

report.php

<?php
require_once 'pages/header.php';
require_once './functions/schema-functions.php';

$course = Schema::getCourse();
$objective = Schema::getObjective();
?>

<form id="addReport" action ='./functions/report-functions.php' method="post">

<table id="table1" class="table">
    <?php
echo '<tr><th>Objectives</th>';
for ($i = 0; $i < count($course); $i++) {
    echo '<th id = "rotate1">'. $course[$i]->commonName . '</th>';            
}
echo '</tr>';

for ($y = 0; $y < count($objective); $y++) {
    echo '<tr><th class=row-header>'.$objective[$y]->objective.'</th>';

for ($x = 0; $x < count($course); $x++) {

    echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$objective[$y]->objectiveId." id=checked></td>";

    }
    echo '</tr>';
}
?>

report-functions.php

 <?php

    if( isset( $_POST['submit'], $_POST['check'] ) ){
    try{

        require_once 'db-connect.php';
        $conn = DatabaseConnection::getConnection();


        $sql='insert into `report`  ( `colrow` ) values ( :value )';
        $stmt = $conn->prepare( $sql );



        if( $stmt ){

            $conn->beginTransaction();

            foreach( $_POST['check'] as $index => $value ) {
                $result = $stmt->execute( [ ':value' => $value ] );
                if( !$result ) {
                    throw new Exception( sprintf( 'Failed to execute query %d for %s', $index, $value ) );
                }
            }

            $conn->commit();
            exit();
        }
    }catch( Exception $e ){
        $conn->rollback();
        exit( $e->getMessage() );
    }
}
?>

I want that after the user submits the data for the first time, the page should load a new table with the previously checked boxes and the user should be able to make the required changed and re-submit it. The database should be updated accordingly.

The criteria given seem a little tenuous and, as there is no real direction given but help was sought, I cobbled together some semi-pseudo code to, perhaps, help you on the way to the end goal ( or some of them anyway )

To edit/delete records you need some manner by which to access them. The simplest would be via querystring pointing to either the same page or a dedicated handler script. The following opts for a dedicated handler.

[ Assume the previous page includes are already included. The important changes here are the addition of the hyperlinks pointing to a new script report-edit.php ]

<form id="addReport" action ='./functions/report-functions.php' method="post">
    <table id="table1" class="table">
        <?php
            echo '<tr><th>Objectives</th>';

            for ( $i = 0; $i < count( $course ); $i++ ) {
                $name=$course[$i]->commonName;
                echo "<th>{$name}</th>";            
            }
            echo '</tr>';

            for( $y = 0; $y < count( $objective ); $y++ ) {

                $objective_title=$objective[$y]->objective;

                echo "<tr>
                    <th class=row-header>{$objective_title}</th>";

                    for ( $x = 0; $x < count( $course ); $x++ ) {

                        $cseid=$course[$x]->courseId;
                        $objid=$objective[$y]->objectiveId;

                        echo "<td>
                            <input name='check[]' type='checkbox' value='c{$cseid}-o{$objid}' />
                            <!-- EDIT LINKS EXAMPLE  -->
                            <a href='./functions/report-edit.php?task=edit&course={$cseid}&objective={$objid}'>Edit</a>
                            <a href='./functions/report-edit.php?task=delete&course={$cseid}&objective={$objid}'>Delete</a>
                        </td>";
                    }
                echo '</tr>';
            }
        ?>
    </table>
</form>

Then, looking at report-edit.php ~ semi-pseudo code.

<?php
    /* report-edit.php */

    $tasks=array('edit','delete');
    $actions=array('commit-edit','commit-delete');

    /* include database connections */
    # require 'db-connect.php';




    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['action'] ) && in_array( $_POST['action'], $actions ) ){

        $course=filter_input( INPUT_POST, 'course', FILTER_SANITIZE_STRING );
        $objective=filter_input( INPUT_POST, 'objective', FILTER_SANITIZE_STRING );
        $value=filter_input( INPUT_POST, 'check', FILTER_SANITIZE_STRING );

        switch( $_POST['action'] ){
            case 'commit-edit':
                /* process form submission */
                $sql='update `report` set `colrow`=:value where `course-id`=:cseid and `objective-id`=:objid';
                /*

                    $args=array(
                        ':value'    =>  $value,
                        ':cseid'    =>  $course,
                        ':objid'    =>  $objective
                    );
                    $stmt=$db->prepare( $sql );
                    $result = $stmt->execute( $args );
                    exit( header( sprintf( 'Location: report.php?action=%s&status=%s', $_POST['action'], $result ) ) );
                */
            break;

            case 'commit-delete':
                /* process form submission */
                $sql='delete from `report` where `course-id`=:cseid and `objective-id`=:objid';
                /*

                    $args=array(
                        ':cseid'    =>  $course,
                        ':objid'    =>  $objective
                    );
                    $stmt=$db->prepare( $sql );
                    $stmt->execute( $args );
                    exit( header( sprintf( 'Location: report.php?action=%s&status=%s', $_POST['action'], $result ) ) );
                */
            break;

            default:
                exit('error');
            break;
        }

        exit( $sql );
    }





    if( $_SERVER['REQUEST_METHOD']=='GET' && !empty( $_GET['task'] ) && in_array( $_GET['task'], $tasks ) ){

        $course=filter_input( INPUT_GET, 'course', FILTER_SANITIZE_STRING );
        $objective=filter_input( INPUT_GET, 'objective', FILTER_SANITIZE_STRING );


        $head="
        <!DOCTYPE html>
        <html>
            <head>
                <title>{$_GET['task']}</title>
            </head>
            <body>";

        $foot="
            </body>
        </html>";


        switch( $_GET['task'] ){
            case 'edit':
            case 'delete':
                /* render a form */
                printf("
                    %s
                    <form method='post'>
                        <h1>%s record</h1>
                        <input type='text' name='course' value='%s' />
                        <input type='text' name='objective' value='%s' />
                        <input type='hidden' name='action' value='commit-%s' />
                        <input type='submit' />
                    </form>
                    %s",
                    $head,
                    ucfirst( $_GET['task'] ),
                    $course,
                    $objective,
                    $_GET['task'],
                    $foot
                );
            break;
            default:
                exit('error');
            break;
        }

    } else {
        http_response_code(404);
    }
?>

Without knowing the schema or the data returned in report.php it is nigh on impossible to give a definitive answer as to how you re-check checkboxes if their value is X ~ nobody barr yourself knows the values held - it could be strings or integers or bits etc etc... so the value of each checkbox might be cbanana-oharvest or c23-o44 etc ... it is unknown!

It is also unknown why the for( $i=0.... syntax for array iteration rather than foreach ? In my mind using for( $i=0; $i... etc opens up possibilities for errors with indices etc. However when it comes to re-checking the checkboxes you need to test if the current row in the database /array equals something else - see previous comment about unknown values though. So, pseudo wise:

if( $row['col-A-value' ]=="A value" && $row['col-B-value']=='B value' ){ $checked=' checked=true'; } else { $checked=''; }

<input name='check[]' type='checkbox' value='c{$cseid}-o{$objid}' {$checked} />

None of the above has been tested more than a rudimentary test and it is, as stated, more pseudo than definitive. The more you put into the question the more you'll get in response I believe for the most part but if you create a new script report-edit.php and add the code below and make changes to report.php you ought to have a better understanding of how to proceed, if not I'll be in the pub!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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