Page 1 of 1

Help needed for passing values

Posted: Wed Apr 29, 2009 10:58 am
by wescrock
Hello,

I am working on a form to Activate/Deactivate post items... I need the form page to display all post items (1-n...) Each post item needs to have 2 check boxes... on submit, the processing php script needs to update all of the entries to toggle the 2 check boxes.

The question is, how do i get my data from the form to the processing script in a way that it can update multiple entries?! I know how to create/edit single entries no problem, but how to I pass the values and process all of them.

Below is the code that I have:

Form:

Code: Select all

<?php
    include 'db.inc';
    $dbh = mysql_connect($hostname, $username, $password) 
    or die("Unable to connect to MySQL");
    
    $sql="SELECT id, type, title, long_title, active, in_archive FROM spotlight.posts";
    $result = mysql_query($sql) or die(mysql_error());
?>
<form method="post" action="process_active.php" enctype="multipart/form-data">
    <table cellspacing="5px" border="1px">
        <tr>
            <th>Visible on Homepage:</th>
            <th>Visible In Archive:</th>
            <th>Spotlight Title:</th>
            <th>RSS Spotlight Title:</th>
        </tr>
<?php   
    while ($row = mysql_fetch_assoc($result)) {
        
        //Translates post type
        if($row[type]==2){
            $post_type='Did You Know: ';
        }elseif($row[type]==3){
            $post_type='Best in Show: ';
        }else{
            $post_type="";
        }
        
        //active value
        if ($row[active}==1){
            $active_check="checked";
        }else{
            $active_check="";
        }
        //in_archive value
        if ($row[in_archive}==1){
            $in_archive_check="checked";
        }else{
            $in_archive_check="";
        }
?>          
        <tr>
            <td><input type="hidden" name="id" value="<?=$row[id]; ?>" ><input type="checkbox" checked="<?=$active_check; ?>" name="active" value="1"  /></td>
            <td><input type="checkbox" checked="<?=$in_archive_check; ?>" name="in_archive" value="1"  /></td>
            <td><?=$post_type.$row[title]; ?></td>
            <td><?=$row[long_title]; ?></td>
        </tr>
<?  } ?></table></form>
Processing Script:

Code: Select all

<?php
        include 'db.inc';
        $dbh = mysql_connect($hostname, $username, $password) 
        or die("Unable to connect to MySQL");
    
    while(???MORE POSTS TO UPDATE???){
        $post_id=$_POST['id'];
        $post_active=$_POST['active'];
        $post_in_archive=$_POST['in_archive'];
        
        //Handle possibilities for ACTIVE/INACTIVE
        if ($post_active==1 && $post_in_archive==1){
            $post_active=1;
            $post_in_archive=1;
        } else if ($post_active==null && $post_in_archive==null){
            $post_active=0;
            $post_in_archive=0;
        } else if ($post_active==null && $post_in_archive==1){
            $post_active=0;
            $post_in_archive=1;
        } else if ($post_active==1 && $post_in_archive==null){
            $post_active=1;
            $post_in_archive=1;
        }
        
        $sql="INSERT INTO spotlight.posts (active, in_archive)
                 VALUES ($post_active, $post_in_archive)
                 WHERE id == $post_id";
        $result = mysql_query($sql) or die(mysql_error());
    
    }
?> 
Thank you so much for any help that you can give!

Re: Help needed for passing values

Posted: Thu Apr 30, 2009 11:08 pm
by McInfo
1. There is an error on line 30 of your form script. The curly brace should be a square bracket. A similar error appears on line 36.

2. Always use quotes around array indexes.

3. Instead of

Code: Select all

<?php $checked = 'checked'; ?>
<input type="checkbox" checked="<?php echo $checked; ?>" />
use

Code: Select all

<?php $checked = ' checked="checked"'; ?>
<input type="checkbox"<?php echo $checked; ?> />
4. Here is an example that I hope answers your question.

Code: Select all

<?php
//---------------------------------------------------------------------------
// Processing
//===========================================================================
?><pre><?php
/*
 * Checks $_POST['ids'] because if all checkboxes are unchecked
 * $_POST['options'] will not be set.
 */
if (isset($_POST['ids'])) {
   
    // For dubugging. Displays the contents of the $_POST array.
    echo '$_POST => ', print_r($_POST, true);
   
    // Loops through all IDs from the form.
    foreach ($_POST['ids'] as $id) {
       
        /*
         * Validates $id before it is inserted in the query.
         * Ensures that $id contains only numberic digits.
         */
        if (!preg_match('/[^0-9]/', $id)) {
           
            // Sets options to 1 if checked, 0 if unchecked
            $option_a = isset($_POST['options'][$id]['option_a']) ? 1 : 0;
            $option_b = isset($_POST['options'][$id]['option_b']) ? 1 : 0;
           
            // Displays a query that updates a table row with the current option values.
            echo "UPDATE `table` SET `option_a` = {$option_a}, `option_b` = {$option_b} WHERE `id` = {$id}"."\n";
        }
    }
}
?></pre><?php
//---------------------------------------------------------------------------
// Form
//===========================================================================
/*
 * Simulates an array of data retrieved from a database.
 * If these were actual database rows and the UPDATE queries had been run
 * before the rows were retrieved, the submitted form values would persist on
 * the next page load.
 */
$data = array
(   0 => array
    (   'id'       => 12
    ,   'title'    => 'Row 12'
    ,   'option_a' => 0
    ,   'option_b' => 1
    )
,   1 => array
    (   'id'       => 13
    ,   'title'    => 'Row 13'
    ,   'option_a' => 1
    ,   'option_b' => 0
    )
);
?>
<form method="post" action="<?php $_SERVER['SCRIPT_NAME']; ?>">
    <table border="1" cellspacing="1" cellpadding="3"><tbody>
        <tr>
            <th>id</th>
            <th>title</th>
            <th>option_a</th>
            <th>option_b</th>
        </tr>
        <?php
        foreach ($data as $row) :
            // If option is enabled, uses checked string. If disabled, uses empty string.
            $checked_a = ($row['option_a'] == 1) ? ' checked="checked"' : '';
            $checked_b = ($row['option_b'] == 1) ? ' checked="checked"' : '';
        ?>
        <tr>
            <td><?php echo $row['id']; ?><input type="hidden" name="ids[]" value="<?php echo $row['id']; ?>" /></td>
            <td><?php echo $row['title']; ?></td>
            <td><input type="checkbox" name="options[<?php echo $row['id']; ?>][option_a]"<?php echo $checked_a; ?> /></td>
            <td><input type="checkbox" name="options[<?php echo $row['id']; ?>][option_b]"<?php echo $checked_b; ?> /></td>
        </tr>
        <?php
        endforeach;
        ?>
        <tr>
            <td colspan="4"><input type="submit" name="btnSubmit" value="Save Options" /></td>
        </tr>
    </tbody></table>
</form>
Edit: This post was recovered from search engine cache.

Re: Help needed for passing values

Posted: Fri May 01, 2009 9:17 am
by wescrock
Hey McInfo. Thank you for the help. I was able to get it working yesterday in a similar (but perhaps less complex manor.)

There was a Tut that I found online that really laid it out clearly.

Thank you for your time and your willingness to help!

Cheers,
Wes

Re: Help needed for passing values

Posted: Fri May 01, 2009 11:26 am
by McInfo
Do you mind sharing your solution and a link to the tutorial? It might be helpful to anyone who comes across this topic looking for a solution to the same problem.

Edit: This post was recovered from search engine cache.

Re: Help needed for passing values

Posted: Fri May 01, 2009 12:05 pm
by wescrock
McInfo wrote:Do you mind sharing your solution and a link to the tutorial? It might be helpful to anyone who comes across this topic looking for a solution to the same problem.
Absolutely! I am not sure where the Tut was... but here is my code:

Form:

Code: Select all

<?php
    include 'db.inc';
    $dbh = mysql_connect($hostname, $username, $password) 
    or die("Unable to connect to MySQL");
    
    $sql="SELECT id, type, title, long_title, active, in_archive FROM spotlight.posts";
    $result = mysql_query($sql) or die(mysql_error());
    
    // start a counter in order to number the input fields for each record
    $i = 0;
    
?>
<form method="post" action="process_active.php" enctype="multipart/form-data">
    <table cellspacing="5px" border="1px">
        <tr>
            <th>Visible on Homepage:</th>
            <th>Visible In Archive:</th>
            <th>Spotlight Title:</th>
            <th>RSS Spotlight Title:</th>
        </tr>
<?php   
    while ($row = mysql_fetch_assoc($result)) {
        
        //Translates post type
        if($row[type]==2){
            $post_type='Did You Know: ';
        }elseif($row[type]==3){
            $post_type='Best in Show: ';
        }else{
            $post_type="";
        }
        
        //active value
        if ($row[active]==1){
            $active_check="checked=\"checked\"";
        }else{
            $active_check="";
        }
        //in_archive value
        if ($row[in_archive]==1){
            $in_archive_check="checked=\"checked\"";
        }else{
            $in_archive_check="";
        }
            
        print "<tr>";
        print   "<td><input type='hidden' name='id[$i]' value='$row[id];' /><input type='checkbox' $active_check; ' name='active[$i]' value='1'  /></td>";
        print   "<td><input type='checkbox' $in_archive_check name='in_archive[$i]' value='1'  /></td>";
        print   "<td>$post_type $row[title]</td>";
        print   "<td>$row[long_title]</td>";
        print "</tr>";
        
        // add 1 to the count, close the loop, close the form, and the mysql connection
        ++$i;
        
    } ?></table><input type='submit' value='Submit Changes' /></form>
Process:

Code: Select all

<?php
        include 'db.inc';
        $dbh = mysql_connect($hostname, $username, $password) 
        or die("Unable to connect to MySQL");
    
        //Gets Count
        $size = count($_POST['id']);
    
        //Starts Loop
        $i = 0;
        while ($i < $size) {
            // define each variable
            $post_id=$_POST['id'][$i];
            $post_active=$_POST['active'][$i];
            $post_in_archive=$_POST['in_archive'][$i];
            
            //Handle possibilities for ACTIVE/INACTIVE
            if ($post_active==1 && $post_in_archive==1){
                $post_active=1;
                $post_in_archive=1;
            } else if ($post_active==null && $post_in_archive==null){
                $post_active=0;
                $post_in_archive=0;
            } else if ($post_active==null && $post_in_archive==1){
                $post_active=0;
                $post_in_archive=1;
            } else if ($post_active==1 && $post_in_archive==null){
                $post_active=1;
                $post_in_archive=1;
            }
            
            $sql="UPDATE spotlight.posts
                     SET active=$post_active, in_archive=$post_in_archive
                     WHERE id=$post_id";
            $result = mysql_query($sql) or die(mysql_error());
            print "$post_id <em>Updated!</em><br /><br />";
            ++$i;
        }
?>
Cheers,
Wes