UPDATE table with checkboxes

I have the option to update what I call "documents" (similar to post creation) on my cms, which works great, but I entered categories where documents are associated with them. Now I was able to link them when creating a document from a new one, but when trying to update them I got a little stuck. I use checkboxes to display a list of categories, and when selected, it updates the junction table that uses doc_id and cat_id.

Here is the script to update the document:

<?php

include ('includes/header.php'); 
require ('../../db_con.php'); 

echo '<h1>Document Edit</h1>';

// Check for a valid document ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_docs.php
    $id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form submission.
    $id = $_POST['id'];
} else { // No valid ID, kill the script.
    echo '<p class="error">This page has been accessed in error.</p>';
    exit();
}


// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $errors = array();

    // Check for a document name:
    if (empty($_POST['doc_name'])) {
        $errors[] = 'You forgot to enter your document name.';
    } else {
        $dn = mysqli_real_escape_string($dbc, trim($_POST['doc_name']));
    }

    // Check for a document content:
    if (empty($_POST['doc_content'])) {
        $errors[] = 'You forgot to enter your last name.';
    } else {
        $dc = mysqli_real_escape_string($dbc, trim($_POST['doc_content']));
    }



    if (empty($errors)) { // If everything OK.

        //  Test for unique doc title:
        $q = "SELECT doc_id FROM docs WHERE doc_name='$dn' AND doc_id != $id";

        $r = mysqli_query($dbc, $q);
        if (mysqli_num_rows($r) == 0) {

            // Make the query:
            $q = "UPDATE docs SET doc_name='$dn', doc_content='$dc', doc_name='$dn' WHERE doc_id=$id LIMIT 1";

            $r = mysqli_query ($dbc, $q);

            if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.




            $doc_id = mysqli_insert_id($dbc); 

            $query = "UPDATE doc_cat_join (cat_id,doc_id) VALUES "; 
            $cat_ids = $_POST['cat_id']; 
            $length = count($cat_ids); 
            for ($i = 0; $i < count($cat_ids); $i++) { 
            $query.='(' . $cat_ids[$i] . ',' . $doc_id . ')'; 

            if ($i < $length - 1) 
            $query.=','; 
            } 




                // Print a message:
                echo '<p>The document has been edited.</p>';    

            } else { // If it did not run OK.
                echo '<p class="error">The document could not be edited due to a system error. We apologize for any inconvenience.</p>'; // Public message.
                echo '<p>' . mysqli_error($dbc) . '<br />Query: ' . $q . '</p>'; // Debugging message.
            }

        } else { // Already used.
            echo '<p class="error">The document name has already been used.</p>';
        }

    } else { // Report the errors.

        echo '<p class="error">The following error(s) occurred:<br />';
        foreach ($errors as $msg) { // Print each error.
            echo " - $msg<br />\n";
        }
        echo '</p><p>Please try again.</p>';

    } // End of if (empty($errors)) IF.

} // End of submit conditional.

// Always show the form...

// Retrieve the document information:
$q = "SELECT * FROM docs WHERE doc_id=$id"; 

$r = mysqli_query ($dbc, $q);

if (mysqli_num_rows($r) == 1) { // Valid document ID, show the form.

    // Get the document information:
    $row = mysqli_fetch_array ($r, MYSQLI_NUM);


    // Create the form:
    echo '<form action="edit_doc.php" method="post">

    <p>Document Name: <input type="text" name="doc_name" size="15" maxlength="15" value="' . $row[1] . '" /></p>

    <textarea name="doc_content" id="doc_content" placeholder="Document Content" style="display: none;"></textarea>
    <iframe name="editor" id="editor" ></iframe>'
        ?>


    <div class="row">
        <div class="col-group-1"> 
            <?php

            $q = "SELECT * FROM cats";  

            $r = mysqli_query ($dbc, $q); // Run the query.

            echo '<div class="view_body">';

            // FETCH AND PRINT ALL THE RECORDS
            while ($row = mysqli_fetch_array($r)) {
            echo '<br><label><input type="checkbox" name="cat_id[]" value="' . $row['cat_id'] . '">' . $row["cat_name"] . '</label>';
            }
            echo '</div>'; 

            ?>
        </div>
    </div>       


    <br><br> 
    <input onclick="formsubmit()" type="submit" value="Update Document" name="submit"/>

    <?php echo'

<input type="hidden" name="id" value="' . $id . '" />
</form>
<br><br><a href="list_doc.php">Back to docs list</a>';

} else { // Not a valid document ID.
    echo '<p class="error">This page has been accessed in error.</p>';
}

?>

<?php
    mysqli_close($dbc);
?>

      

So I have three tables:

docs
  doc_id
  doc_name
  doc_content

cats
  cat_id
  cat_name

doc_cat_join
  doc_id
  cat_id

      

the join table is linked to doc_id and cat_id, which then concatenate them together. I am assuming that in my script, when I update the document, you will need to delete lines and then insert them again? I just need to know the way or the easiest way to update the join table as I'm a little stuck ...

+3


source to share


1 answer


In case of updating a checkbox, you need to remove the previous saved checkbox with the corresponding ID and insert a new checkbox, which you cannot update as we cannot predict how many checkboxes the user will select ....

Happening:

It may happen that the user removes one checkbox during update so that you never know which one needs to be removed .......

In your code ...



docs
   doc_id
   doc_name
   doc_content

cats
   cat_id
   cat_name

doc_cat_join
   id
   doc_id
   cat_id

      

here you need to remove the old checkbox updation doc,

DELETE FROM doc_cat_join WHERE cat_id = some_id

      

Next, you can insert the selected checkbox when you insert the first time ...

+3


source







All Articles