Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

menampilkan bidang data sebagai kotak centang, mempertahankan nilai yang dicentang dan menetapkan nilai sebagai 1 saat dicentang

Tidak yakin apa $type your Anda nilainya hanyalah coba ini dan lihat apakah itu berhasil untuk Anda:

<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>

Catatan:

Tolong, jangan gunakan mysql_* fungsi dalam kode baru . Mereka tidak lagi dipertahankan dan secara resmi tidak digunakan lagi . Lihat kotak merah ? Pelajari tentang pernyataan yang disiapkan sebagai gantinya, dan gunakan PDO , atau MySQLi - artikel ini akan membantu Anda memutuskan yang mana. Jika Anda memilih PDO, inilah tutorial yang bagus .




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. database mysql membuat menu drop down menggunakan data yang sudah dimasukkan di html/php

  2. Laravel - Mengulangi entri dengan parameter unik untuk pengguna yang berbeda

  3. MySQL membuang skrip .sql dan mengimpor ke derby Apache

  4. Mysql:Bagaimana saya bisa menggunakan RTRIM dalam kueri LOAD DATA INFILE saya?

  5. laravel 5.6 memasukkan data json secara massal