将数据字段显示为复选框,选中时保留选中的值并将值设置为1 [英] displaying data fields as checkboxes, retain checked value and set value as 1 when checked

查看:87
本文介绍了将数据字段显示为复选框,选中时保留选中的值并将值设置为1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我有两个表:tbl_checklist和tbl_stud_checklist。一旦我在tbl_checklist中添加了新数据,该项目就会成为tbl_stud_checklist中的另一列。

here, i have two tables: tbl_checklist and the tbl_stud_checklist. once i add new data in the tbl_checklist, that item will be another column in the tbl_stud_checklist.

tbl_checklist:

+---------------------------+
| id  |    Checklist        |
+---------------------------+
| 1   | Medical Certificate |     
| 2   | Evaluation Form     |
| 3   | Application Form    |
+---------------------------+

tbl_stud_checklist:

    +----------------------------------------------------------------+
    | id  | Medical Certificate | Evaluation Form | Application Form |
    +----------------------------------------------------------------+
    | 1   |         0           |         0       |         0        |
    +----------------------------------------------------------------+

然后,我将检索tbl_stud_checklist中的所有数据字段作为复选框,选中该复选框后,将保留该复选框并将其值更改为1。希望您能在这里帮助我。我已经搜索了很多并尝试了很多教程,仍然让我错了。

and then, i will retrieve all data fields in the tbl_stud_checklist as checkboxes, once it was checked, the check will be retained and change its value as 1. hope you can help me outta here. i've searched a lot and tried a lot of tutorials, still getting me wrong.

代码:

<html>
<form action='' method='post'>
<?php
$database = 'sample';
$table = 'tbl_stud_checklist';

$mysql = mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('sample', $mysql) or die(mysql_error($mysql)); // selecting db is not not necessary in this case


$query = sprintf("
    SELECT
        COLUMN_NAME, COLUMN_TYPE
    FROM
        INFORMATION_SCHEMA.COLUMNS
    WHERE
        TABLE_SCHEMA = '%s'
        AND TABLE_NAME = '%s'
",
    mysql_real_escape_string($database),
    mysql_real_escape_string($table)
);
$result = mysql_query($query, $mysql) or die(mysql_error($mysql));


while( false!=($row=mysql_fetch_array($result)) ) {
    $name = htmlspecialchars($row['COLUMN_NAME']);
    $type = htmlspecialchars($row['COLUMN_TYPE']);
    printf("<input type=\"checkbox\" name=\"col[]\" value=\"%s\" />%s (%s)<br />\r\n", $name, $name, $type);
}
?>
<tr><td colspan="2"><input type="submit" name="submit" value="Update Privileges" /></td></tr>
</form>
</html>


推荐答案

不确定您的 $是什么类型的值,但是尝试一下,看看它是否对您有用:

Not sure what your $type values are but try this and see if it works for you:

<html>
<form action='' method='post'>
<?php
$database = 'sample';
$table = 'checklist_stud_columns';
// assuming user_id as 1, you may have to write up more code on 
// how you are fetching this value
$user_id = 1; 
$mysql = mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('sample', $mysql) or die(mysql_error($mysql)); // selecting db is not not necessary in this case

    $query = sprintf("
    SELECT
        COLUMN_NAME,
        COLUMN_TYPE
    FROM
        INFORMATION_SCHEMA.COLUMNS
    WHERE
        TABLE_SCHEMA = '%s'
        AND TABLE_NAME = '%s'
",
    mysql_real_escape_string($database),
    mysql_real_escape_string($table)
);
$result = mysql_query($query) or die(mysql_error());
$name = array();
$type = array();
while( false!=($row=mysql_fetch_array($result)) ) {
    //saving the column name and type in array
    //because it's used in multiple places
    //and we don't want to run the same query again
    if(htmlspecialchars($row['COLUMN_NAME'])!='checklist_id'){
    $name[] = htmlspecialchars($row['COLUMN_NAME']);
    $type[] = htmlspecialchars($row['COLUMN_TYPE']);
    }
}

if(isset($_POST['submit'])) {

        //We need to check if the user id already exists
        //in the table, if it does, we will UPDATE,
        //else INSERT a new record
        $action = '';
        $sql = mysql_query("SELECT * FROM {$table} WHERE checklist_id={$user_id}");
        //if record for the user id is found, update action
        //should take place else insert
        $action = (mysql_num_rows($sql)>0)?'update':'insert';

        if($action=='insert'){
            //INSERT INTO checklist_stud_columns(`id`
            $query_insert = "INSERT INTO {$table}(`id`";

            //INSERT INTO checklist_stud_columns(`id`,`col1`,`col2`
            foreach($_POST['col'] as $val){
                $query_insert .= ",`{$val}`";
            }

            //INSERT INTO checklist_stud_columns(`id`,`col1`,`col2`)
            //VALES(1
            $query_insert .= ") VALUES ({$id}";

            //INSERT INTO checklist_stud_columns(`id`,`col1`,`col2`)
            //VALES(1,1,1
            foreach($_POST['col'] as $val){
                $query_insert .= ",1";
            }

            //INSERT INTO checklist_stud_columns(`id`,`col1`,`col2`)
            //VALES(1,1,1)
            $query_insert .= ")";

            //we have the insert query ready, now executing it
            $result = mysql_query($query_insert) or die(mysql_error());
        }
        elseif($action=='update'){

            if(isset($_POST['col'])){
                //the reason I'm checking if the $_POST['col'] is set is because,
                //you may have checked previously and updated but now you want to
                //uncheck all the options, in that case it's necessary

                foreach($_POST['col'] as $val){

                    //updating the checked values for that $user_id
                    $result = mysql_query("UPDATE checklist_stud_columns SET `{$val}`=1 WHERE checklist_id={$user_id}") or die(mysql_error());

                }

                //this foreach is to check if you have any unchecked values
                //that you had previously checked
                $array_unchecked = array_diff($name,$_POST['col']);
                foreach($array_unchecked as $val){
                    $result = mysql_query("UPDATE checklist_stud_columns SET `{$val}`=0 WHERE checklist_id={$user_id}") or die(mysql_error());
                }
            }
            else
            {
                foreach($name as $val){
                    $result = mysql_query("UPDATE checklist_stud_columns SET `{$val}`=0 WHERE checklist_id={$user_id}") or die(mysql_error());
                }
            }
        }

        if(isset($_POST['col'])){
            //if you had checked atleast one checkbox
            //display with it
            foreach($name as $i=>$n){
                //Displaying all the checkboxes
                //setting checked value to 'checked' if it was checked
                //else setting it to empty ''
                $checked = in_array($n,$_POST['col'])?'checked':'';
                echo "<input type=\"checkbox\" name=\"col[]\" value={$n} {$checked}/>{$n} $type[$i]<br />";
            }
        }
        else {
            foreach($name as $i=>$n){
                echo "<input type=\"checkbox\" name=\"col[]\" value={$n} />{$n} $type[$i]<br />";
            }
        }

    }
    else{
        foreach($name as $i=>$n){
            //Another query that would tell us the value
            //of that column for that $user_id
            $query2 = mysql_query("SELECT {$n} FROM {$table} WHERE checklist_id={$user_id}") or die(mysql_error()); 

            //$query2 = mysql_query("SELECT `{$n}` FROM {$table} WHERE checklist_id={$user_id}") or die(mysql_error());
            if(mysql_num_rows($query2)!=0){
                $row2 = mysql_fetch_array($query2);
                //if the value of that column for that $user_id is 1,
                //set 'checked' else 'empty'
                $checked = ($row2[$n]==1)?'checked':'';
            }
            else 
            {
                $checked = '';
            }
            //display all the checkboxes with
            //the $checked value
            echo "<input type=\"checkbox\" name=\"col[]\" value={$n} {$checked}/>{$n} $type[$i]<br />";
        }
    }
?>
<tr><td colspan="2"><input type="submit" name="submit" value="Update Privileges" /></td></tr>
</form>
</html>



注意:



请不要在新代码中使用 mysql _ * 函数 。它们不再维护并已正式弃用。看到 红色框 ?了解有关 准备好的语句 的信息,并使用 PDO ,或 MySQLi -本文将帮助您确定哪一个。如果选择PDO,请这是一个很好的教程

Note:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

这篇关于将数据字段显示为复选框,选中时保留选中的值并将值设置为1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆