0

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

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.

Code:

<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>
user249563
  • 13
  • 5
  • Where are you getting `$type` from? Also can you describe what exactly you are trying to get after submit? Only the checked checkbox or all the checkboxes with the checked values set? – AyB Mar 01 '14 at 16:40
  • oh im sorry i forgot, it must be $query = sprintf("SELECT COLUMN NAME, COLUMN_TYPE...) then after submit, the checked checkbox will be retained even if i reload the page, and then set the value of that checked checkbox as 1. hope i made it clear to you. – user249563 Mar 01 '14 at 16:51
  • i mean, the displayed checkboxes came from the table column names, so when the user checked it, its value must be 1 in the database .. – user249563 Mar 01 '14 at 17:29
  • Could you show us some sample data from the two tables? One from where you are fetching the records and the other where you are updating. – AyB Mar 02 '14 at 04:11
  • i deleted the code for the submit button, it might make you confused – user249563 Mar 02 '14 at 06:06
  • Can I confirm if there is always 1 record in `tbl_stud_checklist`? If multiple, your `UPDATE` statement would need a `WHERE` clause and more things. – AyB Mar 02 '14 at 06:13
  • there will be multiple records on it, because the id will be set using the id of the users .. – user249563 Mar 02 '14 at 06:17
  • In that case, does your page display checkboxes for multiple users at once (because this would need multiple forms)? or only for one user at a time? If only one user, where are you getting the `id` from? – AyB Mar 02 '14 at 06:22
  • this is only for one user at a time, i get the id from different table named tz_members, i just use $var=SELECT id from tz_members and then update tbl_stud_checklist SET id='$var' something like that .. – user249563 Mar 02 '14 at 06:29
  • Got it, I'll write up a snippet based on this. – AyB Mar 02 '14 at 06:30
  • thank you so much for taking your time on this, i'll also try working on it :)) – user249563 Mar 02 '14 at 06:33

1 Answers1

0

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>

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.

Zoe
  • 27,060
  • 21
  • 118
  • 148
AyB
  • 11,609
  • 4
  • 32
  • 47
  • hi i think i made you confused, the id is not yet on the table, it will be added after the submission, together with the checked column. – user249563 Mar 03 '14 at 02:53
  • @user249563 So it's not an `UPDATE` query but an `INSERT`? – AyB Mar 03 '14 at 04:13
  • @user249563 I've edited my answer with a lot more comments, of course this untested and pretty long too, so you need to work your way out on understanding and making it shorter, again, the above has not been tested so you may have to get back with the errors. Also another thing, the `INSERT` will target only those columns that have been checked, so I recommend you have a `DEFAULT 0` for all the columns in table `tbl_stud_checklist`, this will save more code. – AyB Mar 03 '14 at 05:19
  • :( i keep on getting this error >:( {You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT id from tz_members' at line 1} – user249563 Mar 03 '14 at 11:25
  • @user249563 Can you paste the whole line where you are getting the error? – AyB Mar 03 '14 at 11:27
  • $user_id = "SELECT id from tz_members"; – user249563 Mar 03 '14 at 11:46
  • but when i set $user_id = 1, i got this error, {Unknown column 'Array' in 'field list'} an i don't know where to fix it .. – user249563 Mar 03 '14 at 11:51
  • @user249563 Could you paste the whole code with what you have edited? Think that would be better to point out the mistake. I also don't see anything wrong with your pasted query. – AyB Mar 03 '14 at 11:53
  • i used your code, it's just that i added that query to get the users id. Me too i don't see anything wrong with it .. – user249563 Mar 03 '14 at 11:59
  • @user249563 I think I get it, it's because you are retrieving all the id of the users. You said this page is for updating privilege of one user at a time, correct? – AyB Mar 03 '14 at 12:02
  • i fixed it now :) but i have new error, Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\wamp\www\System\Sadmin\studviewcheck.php on line 276 Unknown column 'id' in 'field list' – user249563 Mar 03 '14 at 12:09
  • @user249563 Does your table `checklist_stud_columns` not have the column `id`? – AyB Mar 03 '14 at 12:10
  • here's the line 276: $action = (mysql_num_rows($sql)>0)?'update':'insert'; – user249563 Mar 03 '14 at 12:10
  • it worked updating the database, but when i try to update new user's, it give me this error {Error! Unknown column 'Array' in 'field list'} – user249563 Mar 03 '14 at 12:35
  • @user249563 Nevermind I figured, in the `else` block, changed `SELECT {$name}` to `SELECT {$n}` – AyB Mar 03 '14 at 12:42
  • i got this {Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\wamp\www\System\Sadmin\studviewcheck.php on line 325} – user249563 Mar 03 '14 at 12:59
  • @user249563 I'm guessing this is coming from the else block (on page load), can you `echo $n;` and see what it prints – AyB Mar 03 '14 at 13:04
  • it displays the first two columns, the checklist_id and Medical Certificate – user249563 Mar 03 '14 at 13:10
  • @user249563 I've added an `if` statement inside the first `while` loop because we do not need the `checklist_id` in our array. And change `$row[$name]` to `$row2[$n]` in the `else` block. If still the same error try to run this query `SELECT {$n} FROM {$table} WHERE id={$user_id}` with the values in your phpMyAdmin. – AyB Mar 03 '14 at 13:18
  • i got this error {Error! Unknown column 'Medical' in 'field list'} – user249563 Mar 03 '14 at 13:54
  • @user249563 It's not a good practice to have space in column names. You should avoid this and use `_` instead. Anyways, I updated the answer yet again. Use backtick '`' in the places where the column names are being mentioned. – AyB Mar 03 '14 at 14:50
  • i changed my column names, already, i still got this error {Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\wamp\www\System\Sadmin\studviewcheck.php on line 329} once i checked 1 item, the value in the database becomes 1, but not retaining the check, that's why the value does not change to 0 once i check it again. – user249563 Mar 03 '14 at 15:18
  • here's the line 329: if(mysql_num_rows($query2>0)){ 330: $row2 = mysql_fetch_array($query2); – user249563 Mar 03 '14 at 15:27
  • @user249563 It's not that line actually, the query before that is failing. Try $query2 = "SELECT `{$n}` FROM {$table} WHERE id={$user_id}"; echo $query2; $query2 = mysql_query($query2) or die(mysql_error()); – AyB Mar 03 '14 at 18:38
  • still have this error {Error! SELECT Medical_Certificate FROM checklist_stud_columns WHERE checklist_id='57' Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\wamp\www\System\Sadmin\studviewcheck.php on line 331}, but its is displaying all the columns except the checklist_id – user249563 Mar 04 '14 at 01:25
  • @user249563 If you try that query on phpMyAdmin, does it work? And yes we have removed `checklist_id` earlier from our array so that's alright. – AyB Mar 04 '14 at 04:23
  • @user249563 Since this seemed to be never-ending, I created a test database just like yours and tried the code, found out the errors I was facing and updated accordingly. More loops and `if` conditions have been added so please try the whole above code. – AyB Mar 04 '14 at 05:16