将类别后的复选框值插入数据库

时间:2015-06-26 13:22:50

标签: php mysql

所以我试图从我的应用程序中的一个表单插入一个文档表中的新行(工作正常),但也在提交时也在连接表中插入一行,我相信我已接近解决问题但仍然能够让它更新连接表。

我在新文档表单中列出了这样的可用类别:

<?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><input type="checkbox" name="cats['.$row['cat_id'].']"> '.$row["cat_name"]. '</label>';
}
echo '</div>'; 

?>

我插入整个表单的脚本如下所示:

<?php
require ('../../db_con.php');

    error_reporting(E_ALL);
    ini_set('display_errors', '1');

// FORM VALIDATION & SUBMISSION
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $errors = array(); // BEGIN AN ERRORS ARRAY

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

    // CHECK LAST NAME
    if (empty($_POST['doc_content'])) {
        $errors[] = 'You forgot to enter any document content.';   
    } else {
        $dc = mysqli_real_escape_string($dbc, trim($_POST['doc_content']));
    }

    // POST CAT ID
    if ($_POST['cat_id']) {
        mysqli_real_escape_string($dbc, trim($_POST['cat_id']));  
    } 


    if (empty($errors)) {

        // MAKING THE QUERY

        $q = "INSERT INTO docs (doc_name, doc_content, created_date) VALUES ('$dn', '$dc', NOW() )";          

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

        if ($r) { 



        mysqli_query($dbc, $query);

            // REDIRECT BACK TO DOCUMENT LIST
            echo("<script>location.href = 'list_doc.php';</script>");

        } else {

            // ERROR CHECKING!
            echo '<h1>System Error!</h1> <p>you could not be registered because of a system error!<br></p>';             

            // DEBUGGIN MESSAGE
            echo '<p>' . mysqli_error($dbc) . '<br><br>query: ' . $q . '</p>';
    }


        $cat_ids=isset($_POST['cats'])&&is_array($_POST['cats'])?array_keys($_POST['cats']):array();

        $query="INSERT INTO cat_doc_join (cat_id,doc_id) VALUES";

        $length=count($cat_ids); 

        for($i=0;$i<$length;$i++){ 
            $query.='('.$cat_ids[$i].','.$doc_id.')'; 

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

        }        


        mysqli_close($dbc);
        exit();

    } else {

        // REPORT THE ERRORS
        echo '<h1>Error!</h1><p class="error">The Following error(s) have occured:<br>';
        foreach ($errors as $msg) {
            echo " - $msg<br>\n";
        }
        echo '</p><p>Please try again!.</p><p><br></p>';

    }

}
?>

我正在努力让连接表进行插入,如果我在$ _POST上做了一个var_dump,我知道它抓住了我选择的所有字段和复选框,但现在插入它的问题。我现在真的很挣扎,所以任何帮助都会感激不尽。

已更新

以下是表格:

<?php

    include 'includes/header.php';
    include 'actions/new_doc.inc.php';

?>



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

            <h1>New document</h1>

            <form action="new_doc.php" method="post">
                <br>
                <input style="width:50%;" placeholder="Document Name" type="text" name="doc_name" autocomplete="off" name="doc_name" value="<?php if(isset($_POST['doc_name'])) echo $_POST['doc_name']; ?>" />

        </div>          
</div>  


<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><input type="checkbox" name="cats['.$row['cat_id'].']"> '.$row["cat_name"]. '</label>';
    }
    echo '</div>'; 

    ?>
    </div>
</div>        


<br>    


<div class="row">
    <div class="col-group-1 wysiwyg_toolbar">    

        <button class="postEditBtn" type="button" onclick="ibold()" title="Bold Text"><i class="fa fa-bold"></i></button>
        <button class="postEditBtn" type="button" onclick="iitalic()" title="Italic Text"><i class="fa fa-italic"></i></button>
        <button class="postEditBtn" type="button" onclick="iunderline()" title="Underline Text"><i class="fa fa-underline"></i></button>
        <button class="postEditBtn" type="button" onclick="ifontName()" title="Font Family"><i class="fa fa-font"></i></button>
        <button class="postEditBtn" type="button" onclick="ifontsize()" title="Font Size"><i class="fa fa-text-height"></i></button>
        <button class="postEditBtn" type="button" onclick="ifontcolor()" title="Font Colour"><i class="fa fa-eraser"></i></button>
        <button class="postEditBtn" type="button" onclick="ihiliteColor()" title="Highlight Text"><i class="fa fa-magic"></i></button>
        <button class="postEditBtn" type="button" onclick="ilink()" title="Add/Edit Link"><i class="fa fa-link"></i></button>
        <button class="postEditBtn" type="button" onclick="iunlink()" title="Remove Link"><i class="fa fa-chain-broken"></i></button>
        <button class="postEditBtn" type="button" onclick="ijustifyLeft()" title="Text align-left"><i class="fa fa-align-left"></i></button>
        <button class="postEditBtn" type="button" onclick="ijustifyCenter()" title="Text align-center"><i class="fa fa-align-center"></i></button>
        <button class="postEditBtn" type="button" onclick="ijustifyRight()" title="Text align-right"><i class="fa fa-align-right"></i></button>
        <button class="postEditBtn" type="button" onClick="iUnorderedList()" title="Unordered List"><i class="fa fa-list-ul"></i></button>
        <button class="postEditBtn" type="button" onClick="iOrderedList()" title="Ordered List"><i class="fa fa-list-ol"></i></button>
        <button class="postEditBtnUndo" type="button" onClick="iUndo()" title="Undo last change"><i class="fa fa-rotate-left"></i></button>
        <button class="postEditBtnRedo" type="button" onClick="iRedo()" title="Redo last change"><i class="fa fa-rotate-right"></i></button>
        <button class="postEditBtn" type="button" onClick="iImage()" title="Image Upload"><i class="fa fa-picture-o"></i></button>

    </div>
</div>


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

                <textarea name="doc_content" id="doc_content" placeholder="Document Content" style="display: none;"></textarea>
                <iframe name="editor" id="editor" style="height: 600px;"></iframe>

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

    </div>
</div>







<p><a href="list_doc.php">Back to document list</a></p>

这是动作脚本:

<?php
require ('../../db_con.php');

    error_reporting(E_ALL);
    ini_set('display_errors', '1');

// FORM VALIDATION & SUBMISSION
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $errors = array(); // BEGIN AN ERRORS ARRAY

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

    // CHECK LAST NAME
    if (empty($_POST['doc_content'])) {
        $errors[] = 'You forgot to enter any document content.';   
    } else {
        $dc = mysqli_real_escape_string($dbc, trim($_POST['doc_content']));
    }

    // POST CAT ID
    if ($_POST['cat_id']) {
        mysqli_real_escape_string($dbc, trim($_POST['cat_id']));  
    } 


    if (empty($errors)) {

        // MAKING THE QUERY

        $q = "INSERT INTO docs (doc_name, doc_content, created_date) VALUES ('$dn', '$dc', NOW() )";          

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

        if ($r) { 


        $cat_ids=isset($_POST['cats'])&&is_array($_POST['cats'])?array_keys($_POST['cats']):array();

        $query="INSERT INTO cat_doc_join (cat_id,doc_id) VALUES";

        $length=count($cat_ids); 

        for($i=0;$i<$length;$i++){ 
            $query.='('.$cat_ids[$i].','.$doc_id.')'; 

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

        }        


        mysqli_query($dbc, $query);
        mysqli_close($dbc);

            // REDIRECT BACK TO DOCUMENT LIST
            echo("<script>location.href = 'list_doc.php';</script>");

        } else {

            // ERROR CHECKING!
            echo '<h1>System Error!</h1> <p>you could not be registered because of a system error!<br></p>';             

            // DEBUGGIN MESSAGE
            echo '<p>' . mysqli_error($dbc) . '<br><br>query: ' . $q . '</p>';
    }

    } else {

        // REPORT THE ERRORS
        echo '<h1>Error!</h1><p class="error">The Following error(s) have occured:<br>';
        foreach ($errors as $msg) {
            echo " - $msg<br>\n";
        }
        echo '</p><p>Please try again!.</p><p><br></p>';

    }

}
?>

1 个答案:

答案 0 :(得分:1)

由于

,您没有进入第二个插入查询
  // REDIRECT BACK TO DOCUMENT LIST
  echo("<script>location.href = 'list_doc.php';</script>");

尝试:

<?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>'; 

?>
<?php 

require ('../../db_con.php'); 

error_reporting(E_ALL); 
ini_set('display_errors', '1'); 

// FORM VALIDATION & SUBMISSION 
if ($_SERVER['REQUEST_METHOD'] == 'POST') { 

$errors = array(); // BEGIN AN ERRORS ARRAY 
// CHECK FIRST NAME 
if (empty($_POST['doc_name'])) { 
$errors[] = 'You forgot to enter a document name.'; 
} else { 
$dn = mysqli_real_escape_string($dbc, trim($_POST['doc_name'])); 
} 

// CHECK LAST NAME 
if (empty($_POST['doc_content'])) { 
$errors[] = 'You forgot to enter any document content.'; 
} else { 
$dc = mysqli_real_escape_string($dbc, trim($_POST['doc_content'])); 
} 

// POST CAT ID 
//if ($_POST['cat_id']) { 
//mysqli_real_escape_string($dbc, trim($_POST['cat_id'])); 
//} 






if (empty($errors)) { 

// MAKING THE QUERY 

$q = "INSERT INTO docs (doc_name, doc_content, created_date) VALUES ('$dn', '$dc', NOW() )"; 

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

if ($r) { 


$doc_id = mysqli_insert_id($dbc); 

$query = "INSERT INTO cat_doc_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.=','; 
} 

mysqli_query($dbc, $query); 
mysqli_close($dbc); 

// REDIRECT BACK TO DOCUMENT LIST 
echo("<script>location.href = 'list_doc.php';</script>"); 
} else { 

// ERROR CHECKING! 
echo '<h1>System Error!</h1> <p>you could not be registered because of a system error!<br></p>'; 

// DEBUGGIN MESSAGE 
echo '<p>' . mysqli_error($dbc) . '<br><br>query: ' . $q . '</p>'; 
} 
} else { 

// REPORT THE ERRORS 
echo '<h1>Error!</h1><p class="error">The Following error(s) have occured:<br>'; 
foreach ($errors as $msg) { 
echo " - $msg<br>\n"; 
} 
echo '</p><p>Please try again!.</p><p><br></p>'; 
} 
} 
?>