Jump to content

Multiple Checkbox Array


dreampho

Recommended Posts

Hi. I have a form with a selection of checkboxes. I am trying to use an array to store the results in a single column of a mysql database. The problem is, instead of the values, it just stores 'array'.

 

Each checkbox is like so:

 

<input name="previous_diseases[]" value="Tuberculosis"/>

 

Here is my code:

 

<?php
try{
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$database = new PDO('mysql:host=localhost;dbname=db', 'username', 'password', $pdo_options);

$execution=$database->prepare('INSERT INTO form(title, forename, surname, address_1, address_2, address_city, address_county, address_country, address_postcode, email, previous_diseases, hear) VALUES(:title, :forename, :surname, :address_1, :address_2, :address_city, :address_county, :address_country, :address_postcode, :email, :previous_diseases, :hear)'); 
$execution->execute(array('title' => $_POST['title'],
         'forename' => $_POST['forename'],
	 'surname' => $_POST['surname'],
         'address_1' => $_POST['address_1'],
	 'address_2' => $_POST['address_2'],
	 'address_city' => $_POST['address_city'],
	 'address_county' => $_POST['address_county'],
	 'address_country' => $_POST['address_country'],
	 'address_postcode' => $_POST['address_postcode'],
	 'email' => $_POST['email'],
	 'previous_diseases' => $_POST['previous_diseases'],
     'hear' => $_POST['hear']));

 

Can anyone please show me what I need to change to get the values inserted into the database.

 

Thank you :)

 

Link to comment
Share on other sites

Are you looking to store all of the results in one record? You said one column. One column could mean one record or multiple records. If you are unsure of the difference, please Google it. Storing an array in one record / one column can be done many different ways, not just with serialize though it is probably the most commonly used method. When the form is submitted, simply check to make sure that form was submitted. Inside the IF statement, serialize() the input method. For example:

 

<?php

$checkBoxes = serialize($_POST['checkbox_input_name']);

?>

Link to comment
Share on other sites

Sorry, I would like to store them all in one record.

 

I have been reading the PHP manual about 'serialize', but I don't quite understand how I could integrate that into the script I posted above. Do you have a suggestion? or possibly show me how?

 

Thanks

Link to comment
Share on other sites

Unfortunately "The Little Guy" is wrong. That would store each item in a separate record, not one record. Nor would it serialize the array. You would want todo something like this:

 

<?php

try {
	$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
	$database = new PDO('mysql:host=localhost;dbname=db', 'username', 'password', $pdo_options);
	$execution = $database->prepare('INSERT INTO form(title, forename, surname, address_1, address_2, address_city, address_county, address_country, address_postcode, email, previous_diseases, hear) VALUES(:title, :forename, :surname, :address_1, :address_2, :address_city, :address_county, :address_country, :address_postcode, :email, :previous_diseases, :hear)');
	$execution->execute(array('title' => $_POST['title'], 'forename' => $_POST['forename'], 'surname' => $_POST['surname'], 'address_1' => $_POST['address_1'], 'address_2' => $_POST['address_2'], 'address_city' => $_POST['address_city'], 'address_county' => $_POST['address_county'], 'address_country' => $_POST['address_country'], 'address_postcode' => $_POST['address_postcode'], 'email' => $_POST['email'], 'previous_diseases' => serialize($_POST['previous_diseases']), 'hear' => $_POST['hear']));
}

?>

 

Notice the addition of the serialize() function around the $_POST['previous_diseases] in your execute line.

Link to comment
Share on other sites

I am very new to PHP and mySQL. I presumed this was the best way.

 

The problem I am having is, the form I am creating has a huge amount of fields. If I was to have each checkbox added separately I would have 100's in my query.

 

I gathered the larger the query the slowly it is.

 

What would be the best direction for me to head in?

 

Thanks to both of you :)

Link to comment
Share on other sites

I personally would setup three database tables. One for the users information and for diseases and a third where the one to many relationship would take place for the users checked diseases. When you display the form, you simply grab the diseases from the diseases table and display a checkbox next to each of them. Using a checkbox array, the unique identifier of the disease would then be used in the name of the checkbox. When the form is submitted an entry into the relationship table would be added with the users unique identifier and the disease unique identifier that was checked.

 

Here is what the tables would look like:

 

--
-- Table structure for table `disease`
--

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=1 ;

--
-- Table structure for table `user`
--

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 ;

--
-- Table structure for table `user_to_disease`
--

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;

Link to comment
Share on other sites

Thank you for your suggestion.

 

Your idea sounds perfect, but to be honest I don't even know how to enter data into more than one table :(

 

If you aren't completely fed up with me yet then it would be great for you to explain how to accomplish all of this, if not thanks for your help so far :)

 

Thanks

Link to comment
Share on other sites

you enter data in to multiple tables the same way you would one table.

 

insert into tableA (col1, col2) values ('value1','value2');
insert into tableB (col1, col2) values ('value1','value2');
insert into tableC (col1, col2) values ('value1','value2');

 

So, now when you want to get users and what disease they have:

 

select * from diseases d left join user_diseases ud on(d.disease_id = ud.disease_id and ud.user_id = 1234) left join users u on(ud.user_id = u.user_id)

 

A query similar to this would give you a list of all the diseases, and if the user has that disease or not.

Link to comment
Share on other sites

Here is your example. There is probably a bit more here than what you are looking for. Please read through it and try to comprehend it. To see this in action simply create a database, import the tables and data, paste the entire contents (comments already in the right place) into a .php file and test. In this example I also show you how to implement a scrollable div box since you were worried about having hundreds of checkboxes on the page and making the form really long.

 

<?php

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

	User registration with error checking and multiple checkbox associations with scrollable div.

	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') {
	$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 . "'");
		}

		$showForm = false;
    	} else {
		$showForm = true;
	}
}

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

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

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

if ($_POST['username']) {
	$username = $_POST['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 Records from Database
						$query = mysql_query("SELECT * FROM disease ORDER BY name ASC") or die('Error: Unable to execute query: ' . mysql_error());

						if ($query) {
							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);
							}
						} else {
							echo '<div class="warning">No results returned</div>';
						}

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

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

<?php mysql_close($link); ?>

</body>
</html>

Link to comment
Share on other sites

Thank you both!

 

@smsmarketeers Thank you so much for taking the time to show me the code. I am in France, so its already afternoon here. I have spent all morning looking at it, trying to work out what everything does, and have not really gotten very far.

 

You have already helped so much! I would really like to understand how to do this, without just copying your code.

 

If you have the time, I would be grateful if you could answer several questions.

 

For my form, there will be several sections that are like 'diseases' with checkboxes, so I am guessing I will need to have a separate table for each?

 

Like I have previously mentioned, I am very new to PHP, but I had an idea that may be easier for me to understand.

Is it possible to set a unique ID to each submission of the form, then have this ID included in each table, say 'user_details', 'disease', 'food_types' etc. Then the diseases and food types would be connected to the users details similar to what you suggested above.

 

If thats so, how could I generate a user id? I have read about uniqid() but dont have a clue how I could incorporate it into my INSERT and VALUE :(

 

Apologies if I am talking rubbish, I am just having real trouble understanding the logic, and how to accomplish all this!!

 

Thanks

 

 

Link to comment
Share on other sites

Mysql has a built in increment value, that for every insert will create an auto incremented unique id. I assume you are using PHPMyAdmin, and to add a field like that, you simply set your "Type" to "INT" and use a "Primary" key, next you Need to set that field to auto increment. There are two different versions of PHPMyAdmin, the newer version uses a checkbox called "AUTO_INCREMENT" or "A_I", the older version uses a drop down box called "Extra".

 

After you create that column, you can insert stuff, which would be like a normal insert query, the only difference is you don't have to use the field you just created in that query, because mysql will automatically add the proper value for you (if you set the field up correctly).

 

Hope this helps!

Link to comment
Share on other sites

dreampho:

 

The code snippet that I wrote for you previously has the database tables setup correctly for auto_increment as TLG mentioned. I urge you, copy the code into a PHP file, save it, create a test database, import the tables and values at the top of the script and execute the script to see how it is working. The easiest way to learn is to implement someone else code and add breaks / exits and echo statements to it to see what it is doing and how it is doing it.

 

In answer to your questions:

 

Thank you both!

 

Question: For my form, there will be several sections that are like 'diseases' with checkboxes, so I am guessing I will need to have a separate table for each?

 

Answer: No, you do not need to have a separate table for each "type" of disease if you are categorizing them. What you can do is a multitude of things. One, you can create a "type" field in the "disease" table and identify each disease with a category name. Of course, you would want to do this without spaces, capitalization and special characters because you will need to refer to them in the array to place them in the correct spots on the page. The other way is to create a separate table for "disease categories" and then use a relationship to categorize them. Then, you would loop through the MySQL query results on the page to place them correctly in categories.

 

Question: Is it possible to set a unique ID to each submission of the form, then have this ID included in each table, say 'user_details', 'disease', 'food_types' etc. Then the diseases and food types would be connected to the users details similar to what you suggested above.

 

Answer: Yes, TLG explained the auto_increment setting in MySQL / phpMyAdmin and I explained above how to do the relationship.

 

You are not talking rubbish however, I do believe that for a beginning what you are trying to do is going to be very difficult in the beginning. If you can master what you are trying to put together then development with PHP will come a lot easier for you. The big thing that most people need to understand about development, especially with PHP, is you need to have commonsense. Writing PHP is just like talking. Let's take an IF statement for instance:

 

$foo = 1;
$bar = 1;

if ($foo == $bar) {
    echo "WE MATCH!";
} else {
    echo "WE DO NOT MATCH";
}

 

The above code snippet would sound like this talking: if foo is definitely equal to bar then WE MATCH otherwise WE DO NOT MATCH. You can take this further as well an explicit state the second else as an ELSEIF. Make sense?

Link to comment
Share on other sites

PHP is like life:

<?php
$is_alive = true;
$hunger_level = 100;
function beat_heart(){
return "Heart: Thump Thump<br>";
}

while($is_alive){
echo beat_heart();
$hunger_level--;
if($hunger_level == 0){
	echo "Eat: Eating food<br>";
}
$revolver_shot = round(rand(0, 6));
if($revolver_shot == 2 || $revolver_shot == 6){
	echo "BANG! You just got shot!<br>";
	$is_alive = false;
}
sleep(1);
}
echo "You are now at your funeral ";
?>

Link to comment
Share on other sites

@The Little Guy! Thank you :)

 

@smsmarketeers, Thank you so much! I have been playing around with the code you provided, trying to work out what each thing does. I have stripped it down, removing the validation, as I already have this, and everything is slowly becoming clear!

 

There are a couple areas I am still a little confused to how they work.

If you dont mind, I have a couple more questions... as always :)

 

For my form I will be needing quite a few more selections of checkboxes, similar to 'diseases', for example 'food_allergies'.

 

I see that there two parts of code seem to control the disease area:

 

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

 

and

 

<?php

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

						if ($query) {
							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);
							}
						} else {
							echo '<div class="warning">No results returned</div>';
						}

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

					?>
					<?php foreach ($results as $disease) { ?>
						<?php $rowClass = ($rowCount % 2) ? $rowTwo : $rowOne; ?>
							<div class="<?php echo $rowClass; ?>"><input name="disease[<?php echo $disease['disease_id']; ?>]" type="checkbox" /><?php echo $disease['name']; ?></div>
						<?php $rowCount++; ?>
					<?php } ?>

 

How would I add more like this?

Would I add a new table called 'food_allergies' and a new column to 'user_disease' ?

 

Could you possibily explain how this code below works?

For instance, if I wanted to have two columns of checkboxes how could I achieve this?

 

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

					?>
					<?php foreach ($results as $disease) { ?>
						<?php $rowClass = ($rowCount % 2) ? $rowTwo : $rowOne; ?>
							<div class="<?php echo $rowClass; ?>"><input name="disease[<?php echo $disease['disease_id']; ?>]" type="checkbox" /><?php echo $disease['name']; ?></div>
						<?php $rowCount++; ?>
					<?php } ?>

 

 

I cant thank you enough for taking your time to help me understand this. :)

 

 

 

 

 

 

 

 

Link to comment
Share on other sites

dreampho:

 

No problem, I am glad that you are starting to understand what you are trying to accomplish a bit better. Because you have another series of checkboxes you would want to add another database table called "user_to_food" or "user_to_allergies" or "user_to_food_allergies". Whatever you name it is entirely up to you. The two columns that would be in the table are "user_id" and "allergy_id" or "food_allergy_id". You will also need a second table called "food_allergies" or "allergies" that will hold the names of the allergies and their unique identifier that will be used in the previous table explained.

 

MySQL is what is called a relational database. What this means is that all records usually have unique identifiers. Those unique identifiers can be used in other tables to associate one record in one table with another record in another table. This is not entirely what "relational database" means but more of a brief description of one way it is used.

 

For the actual code to add another set of checkboxes you will need to duplicate two pieces of code and that code would be the two that you mentioned, of course changing the column names to match those of the new tables in the database that you need to create.

 

As for getting multiple columns in the scrollable DIV what you would want to do is replace the row <div> with a table. I had to do this yesterday in an application that I am working on. My application had to accept a latitude and longitude for a each camera.

 

If you need more help than this please let me know and I will add to the code I already wrote to show you how to accomplish what you are after.

Link to comment
Share on other sites

Thats great! Thank you for your help yet again!

 

The form is now working perfectly. Up until now I have always had the form, and the PHP scripting in two different documents.

In your form, I really like the 'show' and 'hide of the form instead of loading new pages, but I am having issues working out how I can include the scripting I use for my validation and emailing.

 

On previous forms I have used this:

 

$EmailTo = "email@email.com";
$headers .= "From: email@email.com\r\nReply-To: ". strip_tags($_POST['Email']) . "\r\n";
$Subject = "" . ($_POST['forename']) . " " . ($_POST['surname']) . " has completed a Consultation Form";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

$Answer=$_POST['Answer'];
$Yanswer=$_POST['Yanswer'];

$message = '<html><body>';
$message .= '<table rules="all" style="border-color: #FFF;" cellpadding="10">';
$message .= "<tr><td></td><td></td></tr>";
$message .= "<tr><td><strong>Title:</strong> </td><td style='color: #990000;'>" . ($_POST['title']) . "</td></tr>";
$message .= "<tr><td><strong>Name:</strong> </td><td style='color: #990000;'>" . ($_POST['forename']) . " " . ($_POST['surname']) . "</td></tr>";
$message .= "<tr><td><strong>Address:</strong> </td><td style='color: #990000;'>" . ($_POST['address_1']) . "</td></tr>";
$message .= "<tr><td><strong></strong> </td><td style='color: #990000;'>" . ($_POST['address_2']) . "</td></tr>";
$message .= "<tr><td><strong>City:</strong> </td><td style='color: #990000;'>" . ($_POST['address_city']) . "</td></tr>";
$message .= "<tr><td><strong>County:</strong> </td><td style='color: #990000;'>" . ($_POST['address_county']) . "</td></tr>";
$message .= "<tr><td><strong>Country:</strong> </td><td style='color: #990000;'>" . ($_POST['address_country']) . "</td></tr>";
$message .= "<tr><td><strong>Postcode:</strong> </td><td style='color: #990000;'>" . ($_POST['address_postcode']) . "</td></tr>";
$message .= "<tr><td><strong>Email:</strong> </td><td style='color: #990000;'>" . ($_POST['email']) . "</td></tr>";
$message .= "<tr><td><strong>Primary Phone:</strong> </td><td style='color: #990000;'>" . ($_POST['phone_1']) . "</td></tr>";
$message .= "<tr><td><strong>Secondary Phone:</strong> </td><td style='color: #990000;'>" . ($_POST['phone_2']) . "</td></tr>";
$message .= "<tr><td><strong>Currently:</strong> </td><td style='color: #990000;'>" . ($_POST['currently']) . "</td></tr>";
$message .= "<tr><td><strong>Occupation:</strong> </td><td style='color: #990000;'>" . ($_POST['occupation']) . "</td></tr>";
$message .= "<tr><td><strong>Date of Birth:</strong> </td><td style='color: #990000;'>" . ($_POST['dd']) . " / " . ($_POST['mm']) . " / " . ($_POST['yyyy']) . "</td></tr>";
$message .= "<tr><td><strong>Marital:</strong> </td><td style='color: #990000;'>" . ($_POST['marital']) . "</td></tr>";
$message .= "<tr><td><strong>Height:</strong> </td><td style='color: #990000;'>" . ($_POST['height_ft']) . " ft " . ($_POST['height_inches']) . " inches</td></tr>";
$message .= "<tr><td><strong>Weight:</strong> </td><td style='color: #990000;'>" . ($_POST['weight_stone']) . " stone " . ($_POST['weight_kg']) . " kg</td></tr>";
$message .= "<tr><td><strong>Number of Children:</strong> </td><td style='color: #990000;'>" . ($_POST['children']) . "</td></tr>";
$message .= "<tr><td><strong>Doctor:</strong> </td><td style='color: #990000;'>" . ($_POST['doctor']) . "</td></tr>";
$message .= "<tr><td><strong>Allow Contact of Doctor:</strong> </td><td style='color: #990000;'>" . ($_POST['contact_doctor']) . "</td></tr>";
$message .= "<tr><td><strong>Where did you hear about us?</strong> </td><td style='color: #990000;'>" . ($_POST['hear']) . "</td></tr>";
$message .= "</table>";
$message .= "</body></html>";


if ($Answer==$Yanswer){
mail($EmailTo, $Subject, $message,  $headers);
print "<meta http-equiv=\"refresh\" content=\"0;URL=http://www.domain.com\">";}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=http://www.domain.com\">";
}

 

which checks the validation using 'if ($Answer==$Yanswer){' and '$Answer=$_POST['Answer']; $Yanswer=$_POST['Yanswer'];' then stores the information and sends an email.

 

With all the code within one page, as well as the show/hide I have gotten very confused as to how I can incorporate this into the new style of form you have shown me.

 

I simply need it to check the string 'if ($Answer==$Yanswer){' before it sends the data, and if it isn't correct, then load a error message, if it is correct, mail the email and show the message as your form already does.

 

 

I apologise for all the questions! I hope you don't mind.

 

Link to comment
Share on other sites

I fixed the issue above myself.

 

Although I have a new issue, I am not too sure how to display the results, especially with the diseases.

 

Could you possibly show me any example I can work on?

 

Hope you are having a nice weekend!

Link to comment
Share on other sites

Perhaps a couple of questions.

 

How many diseases are there, maximum?

What are the reports you wish to produce? How you store the data depends on how you wish to use the data.

 

For example, if you were merely going to show which diseases a person has, there is no need to be able to search on those diseases, so you can do whatever trick you want to compress the data. For example, you could, if you wished, create a binary representation of the options, and store the results of your check boxes as a binary number. Then, when display, decode that binary number and show the diseases.

 

But, if you wish to do analysis on the diseases, then the master / child relationship is a very good one, because though there many be thousand potential diseases, a person normally won't have more than a small subset of those, or one would hope.  ::) So, the examples you are getting with two tables are very good.

 

If you develop other attributes, you would wish to put them either in another table, or change your disease table to be something more generic, and a code to say whether it is a disease, an alergy, an injury, etc.

 

hope that helps.

Link to comment
Share on other sites

This is really going to depend on how you want to display the information. Did you want to display it in an editable for so that members can update their records or did you just want to display the information in a text formatted way on the screen?

 

I fixed the issue above myself.

 

Although I have a new issue, I am not too sure how to display the results, especially with the diseases.

 

Could you possibly show me any example I can work on?

 

Hope you are having a nice weekend!

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.