Jump to content

[SOLVED] Problem updating checkboxes in PHP/MySQL application. Please help.


JsusSalv

Recommended Posts

Hello:

 

I need a little help here with some basic PHP coding.  Basically, I have an application that allows users to create a profile.  The profile has a series of checkboxes with different categories.  These categories are a result of records stored in a MySQL database table called 'categories'.

Upon creating a profiel the users can tick as many checkboxes that apply to him/her.  They can then submit the profile.  The codes I've created successfully grabs all the checkboxes that were ticked and enters the records into a MySQL database table called `clients`.  However, this is where I'm having difficulty...when a user goes to tupdate his/her profile all the checkboxes are empty.  For some strange reason I can't seem to figure out how to code the proper script for displaying previously selected checkboxes for the user.

Once a user saves his/her profile the first time I can then check the database and see that their categories are listed in the table called 'clients'.  But when they go to udpate it gets wiped out.

 

Here's the code I have for updating the profile.  Thank you!

 

<?php
include('database_connection.php');

// Prepare an array of expected items.
$expected = array('client_id', 'name', 'email', 'category');


// Get details of selected record.
if ($_GET && !$_POST) {
  if (isset($_GET['client_id']) && is_numeric($_GET['client_id'])) {
    $client_id = $_GET['client_id'];
}
  else {
    $client_id = NULL;
}
  if ($client_id) {
    $sql = "SELECT * FROM client WHERE client_id = $client_id";
  $result = mysql_query($sql) or die (mysql_error());
  $row = mysql_fetch_assoc($result);
}
  }
  

// Category: Build checkbox list with contents from 'categories' table
$allCats = "SELECT * FROM categories";
$catList = mysql_query($allCats) or die (mysql_error());


  
// If form has been submitted, update record.
if (array_key_exists('update', $_POST)) {
  // prepare expected items for insertion in to database
  foreach ($_POST as $key => $value) {
    if (in_array($key, $expected)) {
      ${$key} = mysql_real_escape_string($value);
      }
    }
  // Abandon the process if primary key is invalid.
  if (!is_numeric($client_id)) {
    die('Invalid request');
}

  $categories=$_POST['category']; // Data captured from post operation.
  $cat_isset = isset($categories) ? $categories : array('None Selected');
  $category = implode($cat_isset, ",");

  // Prepare the first SQL query.
  $sql = "UPDATE client SET name = '$name', email = '$email', category = '$category' WHERE client_id = $client_id";

  // Submit the query and redirect if successful.
  $done = mysql_query($sql) or die(mysql_error());
  }

// Redirect page on success or if $article_id is invalid.
if ($done || !isset($client_id)) {
  header('Location: ./clients.php');
  exit;
  }

print '<?xml version="1.0" encoding="UTF-8"?>';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en-us" xml:lang="en-us" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
<meta http-equiv="Content-Language" content="en-us" />
<title>Update Client</title>
</head>
<body>
<h1>Update Client</h1>
<p><a href="./clients.php">Back to Client List</a></p><br />
<br />
<?php if (empty($row)) {
?>
<p class="warning">Invalid request: record does not exist.</p>
<?php } 
else {
?>
<form id="form1" name="form1" method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
  <div style="width:100%; margin: 0 0 0.5em; 0;">
  <div style="float:left; width:15%; text-align: right; font-weight:bold; margin: 0 0.3em 0 0;"><label for="name">Name:</label></div>
  <div style="float:left; width:80%;"><input type="text" name="name" id="name" size="50"  value="<?php echo htmlentities($row['name']); ?>" /></div>
  <br clear="both">
  </div>

  <div style="width:100%; margin: 0 0 0.5em; 0;">
  <div style="float:left; width:15%; text-align: right; font-weight:bold; margin: 0 0.3em 0 0;"><label for="email">Email:</label></div>
  <div style="float:left; width:80%;"><input type="text" name="email" id="email" size="50" value="<?php echo htmlentities($row['email']); ?>" /></div>
  <br clear="both">
  </div>

  <div style="width:100%; margin: 0 0 0.5em; 0;">
  <div style="float:left; width:15%; text-align: right; font-weight:bold; margin: 0 0.3em 0 0;"><label for="category">Categories:</label></div>
  <div style="float:left; width:80%;">
<table>
	<?php
          while ($cat = mysql_fetch_assoc($catList)) {
        ?>
  <tr>
	<td>
        <input type="checkbox" name="category[]" id="category[]" value="<?php echo $cat['category']; ?>"
        <?php
          // Get all categories from 'categories' table
          $list = $cat['category'];

          // Grab all categories listed for this client from the 'clients' table.
          $check = explode(',',$row['category']); 

          //Place the results of $check into a foreach loop.
	  foreach($check as $checked) {
            if (isset($checked) && in_array($checked, $list))	{
            echo 'checked="checked"';
            }
          ?>
	/><?php echo $cat['category']; ?>
	</td>
        <?php } ?>
  </tr>
</table>
  </div>
  <br clear="both">
  </div>

  <div style="width:100%; margin: 0 0 0.5em; 0;">
    <input type="submit" name="update" value="UPDATE CLIENT" />
    <input name="client_id" type="hidden" value="<?php echo $row['client_id']; ?>" />
    <input TYPE="button" onClick="parent.location='clients.php'" value="CANCEL">
  <br clear="both">
</form>
<?php } ?>
</body>
</html>

Just as a heads up, I'm usually flying through these forums, and rarely get a chance to look over a big clump of code even if it's just for a simple issue. If you can isolate your code down to only what's causing you trouble, you'll get help sooner.

 

$catList = mysql_query($allCats) or die (mysql_error());
echo "<h3>Categories</h3>\n";
while( $cat = mysql_fetch_assoc($catList) )
echo '<input type="checkbox" name="category" value="'.$cat['name'].'" />'.$cat['name']."<br />\n";

Thanks, I'll give this a try.  I used to post smaller chunks of code...then I was reprimanded because I didn't post enough of my code.  Crazy eh?  I'll try to find a middle ground.  I'll let you know if if worked for me.  Thanks!

Have you viewed the source of the page to see if the "checked='checked'" is there? If it's not, it has to be something with the check you're doing to see if it needs to be checked. Re-post that block of code and explain what each variable/array should contain.

I fixed my own problem.  Here's the code I used...thanks everyone for the help!

            <td>
            <input type="checkbox" name="category[]" id="category[]" onclick="checkAllFields(2);" value="<?php echo $cat['category']; ?>"
              <?php
       		    $catcheck = explode(',',$cat['category']);          
                  foreach($catcheck as $catchecked)
       		    $check = explode(',',$row['category']); 
                  foreach($check as $checked)
                    if ($catchecked == $checked)  {echo 'checked="checked"';}
              ?>
            /><?php echo $cat['category']; ?>
    		</td>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.