Php 将数据字段显示为复选框,选中时保留选中值并将值设置为1

Php 将数据字段显示为复选框,选中时保留选中值并将值设置为1,php,mysql,checkbox,Php,Mysql,Checkbox,在这里,我有两张表格:tbl_清单和tbl_清单。一旦我在tbl_清单中添加了新数据,该项目将成为tbl_清单中的另一列 tbl_检查表: tbl_螺栓检查表: 然后,我将检索tbl_stud_清单中的所有数据字段作为复选框,一旦选中,该复选框将被保留并将其值更改为1。希望你能帮我离开这里。我已经搜索了很多,尝试了很多教程,但还是弄错了 代码: 不确定您的$type值是什么,但尝试一下,看看它是否适合您: <html> <form action='' method='post'

在这里,我有两张表格:tbl_清单和tbl_清单。一旦我在tbl_清单中添加了新数据,该项目将成为tbl_清单中的另一列

tbl_检查表:

tbl_螺栓检查表:

然后,我将检索tbl_stud_清单中的所有数据字段作为复选框,一旦选中,该复选框将被保留并将其值更改为1。希望你能帮我离开这里。我已经搜索了很多,尝试了很多教程,但还是弄错了

代码:

不确定您的$type值是什么,但尝试一下,看看它是否适合您:

<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>
注:
。它们不再得到维护。看到了吗?相反,学习,并使用,或-将帮助您决定哪一个。如果您选择PDO,.

您从哪里获得$type?你能描述一下你提交后想要得到什么吗?只有选中的复选框或设置了选中值的所有复选框?哦,很抱歉我忘记了,它必须是$query=sprintfSELECT COLUMN NAME,COLUMN\u TYPE。。。然后在提交后,即使我重新加载页面,选中的复选框也将保留,然后将该复选框的值设置为1。希望我向您说明清楚。我的意思是,显示的复选框来自表的列名,因此当用户选中它时,它在数据库中的值必须为1。您可以向我们展示两个表中的一些示例数据吗?一个是从获取记录的地方,另一个是更新的地方。请查看我编辑的问题。我想我把你弄糊涂了,id尚未在表上,它将在提交后添加,与选中列一起。@user249563所以这不是更新查询,而是插入?@user249563我用更多的注释编辑了我的答案,当然这没有经过测试,也很长,所以你需要设法理解并缩短它,同样,上面的内容还没有经过测试,因此你可能不得不返回错误。还有一件事,INSERT将只针对那些已检查的列,因此我建议您为表tbl_stud_checklist中的所有列设置默认值0,这将节省更多代码。:我继续收到此错误>:{您的SQL语法有错误;请检查与您的MySQL服务器版本相对应的手册,以了解在第1行}@user249563的“SELECT id from tz_members”附近使用的正确语法。您能将整行粘贴到出现错误的地方吗?
    +----------------------------------------------------------------+
    | id  | Medical Certificate | Evaluation Form | Application Form |
    +----------------------------------------------------------------+
    | 1   |         0           |         0       |         0        |
    +----------------------------------------------------------------+
<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>
<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>