sql >> Databáze >  >> RDS >> Mysql

zobrazení datových polí jako zaškrtávacích políček, ponechat zaškrtnutou hodnotu a nastavit hodnotu jako 1 při zaškrtnutí

Nejste si jisti, jaký máte $type hodnoty jsou, ale zkuste toto a uvidíte, zda vám to funguje:

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

Poznámka:

Prosím, nepoužívejte mysql_* funkce v novém kódu . Již nejsou udržovány a jsou oficiálně ukončeny . Viz červený rámeček ? Další informace o připravených prohlášeních místo toho a použijte CHOP nebo MySQLi - tento článek vám pomůže rozhodnout, které. Pokud zvolíte PDO, zde je dobrý návod .




  1. selectionArgs v SQLiteQueryBuilder nefunguje s celočíselnými hodnotami ve sloupcích

  2. Dotaz MySQL pro vyhledávání položek s určitými značkami

  3. Jak spočítat počet nenásledujících hodnot ve sloupci pomocí SQL?

  4. Příkaz přípravy MySql - je možné parametrizovat název sloupce nebo název funkce?