Jump to content

Multiple Checkbox Array


dreampho

Recommended Posts

@smsmarketeers

 

Thanks for your reply.

 

I think what I want to display is going to be rather difficult, which is why I thought I should ask for your help/advice.

 

I was hoping to display lists of all the users names in alphabetical order. Click on a name and it would show all of their information non editable, then have a link to edit.

 

I think this is going to be very difficult, but I would love to learn how.

 

Any guidance/examples/help would be fantastic :)

Link to comment
Share on other sites

@dreampho: Neither of those is really that difficult. The easiest thing to do for editing is to copy your registration form. Then, add code to select all of the "diseases" that the user had selected during registration from the database. Put them into an array and, while looping through all of the "diseases", check to see if the "disease" was checked by using checking to see if the diseases unique identifier exists in the array. If it does, make the box checked. If it does not, then the box is not checked. I do this using jQuery most of the time because I am pulling results using an API from another system but it does not have to be done that way. If you are confused, check out the in_array() function and let me know if you need an example.

 

http://php.net/manual/en/function.in-array.php

Link to comment
Share on other sites

@smsmarketeers

 

Thank you for your reply. I have looked at the in_array but am still confused :(

 

It would be great if you could give me an example how I could achieve all this. I wish I thought it was as easy as you do! :P

 

Thanks

Link to comment
Share on other sites

@dreampho:

 

Here is you go. Here is your example. This uses the same database and tables as before. This script will allow you to create a user, then it will redirect to the edit portion using the exact same form. All fields except the password are automatically filled in and you can change the diseases.

 

<?php

/*
	Written By: SMS Marketeers
	Website: http://www.smsmarketeers.com

	User registration with error checking and multiple checkbox associations with scrollable div but in editable format. This
	script takes a user_id GET parameter in the URL.

	Database Structure

	CREATE TABLE IF NOT EXISTS `disease` (
	`disease_id` int(11) NOT NULL AUTO_INCREMENT,
	`name` varchar(64) COLLATE utf8_bin NOT NULL,
	PRIMARY KEY (`disease_id`)
	) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=5 ;

	INSERT INTO `disease` (`disease_id`, `name`) VALUES (1, 'HIV / AIDS'), (2, 'Tuberculosis'), (3, 'Malaria'), (4, 'Cancer');

	CREATE TABLE IF NOT EXISTS `user` (
	`user_id` int(11) NOT NULL AUTO_INCREMENT,
	`firstname` varchar(32) CHARACTER SET latin1 NOT NULL,
	`lastname` varchar(32) CHARACTER SET latin1 NOT NULL,
	`email` varchar(96) CHARACTER SET latin1 NOT NULL,
	`username` varchar(32) CHARACTER SET latin1 NOT NULL,
	`password` varchar(32) CHARACTER SET latin1 NOT NULL,
	`date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
	PRIMARY KEY (`user_id`)
	) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ;

	CREATE TABLE IF NOT EXISTS `user_to_disease` (
	`user_id` int(11) NOT NULL,
	`disease_id` int(11) NOT NULL
	) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
*/

// Define Database Variables
$dbHostname = 'localhost';
$dbUsername = 'username';
$dbPassword = 'password';
$dbDatabase = 'database';

// Establish Database Connection
$dbCon = mysql_connect($dbHostname, $dbUsername, $dbPassword) or die('Error: Unable able to connect: ' . mysql_error());

// Select Working Database
$dbSel = mysql_select_db($dbDatabase, $dbCon) or die('Error: Unable to select database: ' . mysql_error());

// Handle POST
$error = array();
$showForm = true;

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_GET['user_id'])) {
	$emailPattern = '/^[A-Z0-9._%\-+]+@[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z]{2,6}$/i';

	// Validate fields first
	if (empty($_POST['firstname'])) {
		$error['firstname'] = '<strong>Error:</strong> First Name is a required field!';
	}

	if (empty($_POST['lastname'])) {
		$error['lastname'] = '<strong>Error:</strong> Last Name is a required field!';
	}

	if (empty($_POST['email']) || (!preg_match($emailPattern, $_POST['email']))) {
		$error['email'] = '<strong>Error:</strong> Either the email address was left blank or is not valid!';
	}

	if (empty($_POST['username'])) {
		$error['username'] = '<strong>Error:</strong> Username is a required field!';
	}

    	if (!$error) {
		mysql_query("UPDATE user SET firstname = '" . $_POST['firstname'] . "', lastname = '" . $_POST['lastname'] . "', email = '" . $_POST['email'] . "', username = '" . $_POST['username'] . "', date = NOW()") or die('Error: Unable to execute query: ' . mysql_error());

		// Insert Diseases
		mysql_query("DELETE FROM user_to_disease WHERE user_id = '" . (int)$_GET['user_id'] . "'");

		foreach ($_POST['disease'] AS $key => $value) {
			mysql_query("INSERT INTO user_to_disease SET user_id = '" . (int)$_GET['user_id'] . "', disease_id = '" . (int)$key . "'");
		}

		$showForm = true;
    	} else {
		$showForm = true;
	}
} elseif ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_GET['user_id'])) {
	$emailPattern = '/^[A-Z0-9._%\-+]+@[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z]{2,6}$/i';

	// Validate fields first
	if (empty($_POST['firstname'])) {
		$error['firstname'] = '<strong>Error:</strong> First Name is a required field!';
	}

	if (empty($_POST['lastname'])) {
		$error['lastname'] = '<strong>Error:</strong> Last Name is a required field!';
	}

	if (empty($_POST['email']) || (!preg_match($emailPattern, $_POST['email']))) {
		$error['email'] = '<strong>Error:</strong> Either the email address was left blank or is not valid!';
	}

	if (empty($_POST['username'])) {
		$error['username'] = '<strong>Error:</strong> Username is a required field!';
	}

	if (empty($_POST['password'])) {
		$error['password'] = '<strong>Error:</strong> Password is a required field!';
	}

	if (empty($_POST['confirm']) || $_POST['confirm'] != $_POST['password']) {
		$error['confirm'] = '<strong>Error:</strong> Confirm is a required field and must match password!';
	}

    	if (!$error) {
		mysql_query("INSERT INTO user SET firstname = '" . $_POST['firstname'] . "', lastname = '" . $_POST['lastname'] . "', email = '" . $_POST['email'] . "', username = '" . $_POST['username'] . "', password = '" . md5($_POST['password']) . "', date = NOW()") or die('Error: Unable to execute query: ' . mysql_error());

		$user_id = mysql_insert_id();

		// Insert Diseases
		foreach ($_POST['disease'] AS $key => $value) {
			mysql_query("INSERT INTO user_to_disease SET user_id = '" . (int)$user_id . "', disease_id = '" . (int)$key . "'");
		}

		header('Location: user_registration_multi_checkbox_edit.php?user_id=' . $user_id);
    	} else {
		$showForm = true;
	}
}

// Check URL parameters for user_id
if (empty($_GET['user_id'])) {
	$error['missing_user_id'] = 'Error: Missing user_id in query parameters.';
} elseif ($_GET['user_id']) {
	$query = mysql_query("SELECT DISTINCT * FROM user WHERE user_id = '" . (int)$_GET['user_id'] . "'");
	$result = mysql_fetch_assoc($query);
}

// Setup input variables
if ($_POST['firstname']) {
	$firstname = $_POST['firstname'];
} elseif ($result['firstname']) {
	$firstname = $result['firstname'];
} else {
	$firstname = '';
}

if ($_POST['lastname']) {
	$lastname = $_POST['lastname'];
} elseif ($result['lastname']) {
	$lastname = $result['lastname'];
} else {
	$lastname = '';
}

if ($_POST['email']) {
	$email = $_POST['email'];
} elseif ($result['email']) {
	$email = $result['email'];
} else {
	$email = '';
}

if ($_POST['username']) {
	$username = $_POST['username'];
} elseif ($result['username']) {
	$username = $result['username'];
} else {
	$username = '';
}

?>

<html>
<head>
<title>User Registration</title>
<style type="text/css">
	*		{ font-size:12px; font-family:Arial; margin:0px; outline:0px; padding:0px; }
	body	{ background:#ffffff; color:#000000; margin:10px 0px 0px 0px; }
	img		{ border:0px; }
	p		{ margin:5px 0px 10px 0px; }
	form	{ border:none; margin:0px; padding:0px; }

	a				{ cursor:pointer; }
	a:link			{ color:#9AB324; text-decoration:none; }
	a:visited		{ color:#9AB324; text-decoration:none; }
	a:hover 		{ color:#9AB324; text-decoration:underline; }
	a:active 		{ color:#9AB324; text-decoration:none; }

	.container		{ margin:0px auto; width:700px; }
	.success		{ background:#EEF5CD; border:1px dashed #9AB324; color:#608339; margin-bottom:5px; padding:5px; text-align:left; }
	.warning		{ background:#eed4d2; border:1px dashed #a94637; color:#ac241a; margin-bottom:5px; padding:5px; text-align:left; }
	.attention		{ background:#fefbcc; border:1px dashed #e6db55; color:#ada019; margin-bottom:5px; padding:5px; text-align:left; }

	form, fieldset			{ border:none; margin:0px; padding:0px; }
	input, textarea, select { font:100% arial, sans-serif; vertical-align:middle; }
	input[type='text']		{ background:#ffffff; border:1px solid #c3c3c3; border-left-color:#7c7c7c; border-top-color:#7c7c7c; padding:2px; }
	input[type='password']	{ background:#ffffff; border:1px solid #c3c3c3; border-left-color:#7c7c7c; border-top-color:#7c7c7c; padding:2px; }
	input[type='radio']		{ margin:0px 5px 0px 5px; }
	input[type='hidden']	{ display:none !important; }
	select					{ border:1px solid #c3c3c3; border-left-color:#7c7c7c; border-top-color:#7c7c7c; min-width:100px; padding:1px; }
	select option			{ padding:0px 5px 0px 5px; }
	textarea				{ background:#ffffff; border:1px solid #c3c3c3; border-left-color:#7c7c7c; border-top-color:#7c7c7c; padding:2px; }

	table.form th				{ background:#9AB324; border-bottom:1px solid #596E0E; color:#ffffff; font-weight:bold; padding:5px; text-align:center; }
	table.form td				{ padding:5px; }
	table.form td.colOne		{ background:#f0f0f0; border-bottom:1px solid #dddddd; }
	table.form td.colTwo		{ background:#f5f5f5; border-bottom:1px solid #dddddd; }
	table.form td.button		{ background:#ffffff; border:none; text-align:right; }

	.scrollbox				{ background:#ffffff; border:1px solid #bbbbbb; height:100px; overflow-y:scroll; width:350px; }
	.scrollbox div			{ padding:5px; }
	.scrollbox div input	{ margin:0px; margin-right:5px; padding:0px; }
	.scrollbox div.rowOne	{ background:#ffffff; border-bottom:1px solid #dddddd; }
	.scrollbox div.rowTwo	{ background:#f5f5f5; border-bottom:1px solid #dddddd; }
</style>
</head>
<body>

<div class="container">
<?php if ($showForm == true) { ?>
	<form action="" method="POST" name="form" id="form">
		<div class="attention">User registration with error checking and multiple checkbox associations with scrollable div.</div>

		<table align="center" border="0px" cellpadding="0px" cellspacing="1px" class="form" width="700px">
			<tr>
				<td class="colOne" width="150px">First Name:</td>
				<td class="colTwo">
					<input name="firstname" type="text" value="<?php echo $firstname; ?>" />
					<?php if ($error['firstname']) { ?><span class="warning"><?php echo $error['firstname']; ?></span><?php } ?>
				</td>
			</tr>
			<tr>
				<td class="colOne">Last Name:</td>
				<td class="colTwo">
					<input name="lastname" type="text" value="<?php echo $lastname; ?>" />
					<?php if ($error['lastname']) { ?><span class="warning"><?php echo $error['lastname']; ?></span><?php } ?>
				</td>
			</tr>
			<tr>
				<td class="colOne">Email Address:</td>
				<td class="colTwo">
					<input name="email" type="text" value="<?php echo $email; ?>" />
					<?php if ($error['email']) { ?><span class="warning"><?php echo $error['email']; ?></span><?php } ?>
				</td>
			</tr>
			<tr>
				<td class="colOne">Username:</td>
				<td class="colTwo">
					<input name="username" type="text" value="<?php echo $username; ?>" />
					<?php if ($error['username']) { ?><span class="warning"><?php echo $error['username']; ?></span><?php } ?>
				</td>
			</tr>
			<tr>
				<td class="colOne">Password:</td>
				<td class="colTwo">
					<input name="password" type="password" value="" />
					<?php if ($error['password']) { ?><span class="warning"><?php echo $error['password']; ?></span><?php } ?>
				</td>
			</tr>
			<tr>
				<td class="colOne">Confirm Password:</td>
				<td class="colTwo">
					<input name="confirm" type="password" value="" />
					<?php if ($error['confirm']) { ?><span class="warning"><?php echo $error['confirm']; ?></span><?php } ?>
				</td>
			</tr>
			<tr>
				<td class="colOne" valign="top">Previous Disease(s):</td>
				<td class="colTwo">
					<div class="scrollbox" style="height:100px; width:100%;">
					<?php

						// Select All Disease Records from Database
						$query = mysql_query("SELECT * FROM disease ORDER BY name ASC") or die('Error: Unable to execute query: ' . mysql_error());

						if (is_resource($query)) {
							$i = 0;
							$data = array();

							while ($result = mysql_fetch_assoc($query)) {
								$data[$i] = $result;
								$i++;
							}

							mysql_free_result($query);

							$results = array();
							$results = $data;

							unset($data);
						}

						// Select All Use Disease Records from Database
						$query = mysql_query("SELECT * FROM user_to_disease WHERE user_id = '" . (int)$_GET['user_id'] . "'");

						while ($row = mysql_fetch_assoc($query)) {
							$user_diseases[] = $row['disease_id'];
						}

						$rowOne = 'rowOne';
						$rowTwo = 'rowTwo';
						$rowCount = 0;

					?>
					<?php foreach ($results as $disease) { ?>
						<?php $rowClass = ($rowCount % 2) ? $rowTwo : $rowOne; ?>
							<div class="<?php echo $rowClass; ?>">
								<?php if (in_array($disease['disease_id'], $user_diseases)) { ?>
									<input name="disease[<?php echo $disease['disease_id']; ?>]" type="checkbox" checked="checked" /><?php echo $disease['name']; ?>
								<?php } else { ?>
									<input name="disease[<?php echo $disease['disease_id']; ?>]" type="checkbox" /><?php echo $disease['name']; ?>
								<?php } ?>
							</div>
						<?php $rowCount++; ?>
					<?php } ?>
					</div>
				</td>
			</tr>
			<tr><td class="button" colspan="4">
				<?php if (isset($_GET['user_id'])) { ?>
					<input name="submit" type="submit" value="Update Profile" />
				<?php } else { ?>
					<input name="submit" type="submit" value="Create Profile" />
				<?php } ?>
			</td></tr>
		</table>
	</form>
<?php } elseif ($showForm == false) { ?>
	<?php if (isset($_GET['user_id'])) { ?>
		<div class="success">User updated successfully.</div>
	<?php } else { ?>
		<div class="success">Thank you for your registration.</div>
	<?php } ?>
<?php } ?>
</div>

<?php mysql_close($link); ?>

</body>
</html>

Link to comment
Share on other sites

Thank you very much for your example code. By using your code as an example I am able to decipher how the coding works, which I am slowly starting to understand. I have managed to get my form working!!

 

Unfortunately I have yet another confused look on my face. I have been reading all over the internet today trying to work out how to retrieve information from the tables, having little luck.

 

What I want, is to display a list of users names which each link to a page that displays all of the users details in a table, and has an edit details button (which would take me back to the users form)

 

I know that you must be busy, but it would be fantastic if you could show me how I could do this with some example code!

 

Your help is very much appreciated!!

 

 

Link to comment
Share on other sites

My last code example does what you are asking to do for the most part. If you copy and paste the code into a PHP file directly, setup the database, and you will see it work. Basically what you want to do is pass the user_id through the URL parameters and then, using $_GET['user_id'], SELECT * FROM users WHERE user_id = $_GET['user_id'].

 

As for displaying the username's and user_id's in a table as a link, you need to SELECT * FROM users then loop through the results and display them.

Link to comment
Share on other sites

@smsmarketeers

 

I set up your code and database yesterday and it really helped me figure out how to get my form to display the results saved previously.

 

I have been staring at the code since you posted a couple hours ago... and I just cant make head nor tail of how I can display just the results.

 

I know this is a tall order, but would it be pushing it too far if I was to ask you to show me an example. I think all of this is way beyond my understanding... I barely know how to display results, let alone like this.

 

If you don't have time then no worries.

 

Thanks again, and forgive my incompetence ;)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.