Dynamically generate checkbox form based on database records - php

Hi so I have two tables in my database and they are structured as follows:
1) services Table:
service_id, service_name
2) business_services_offered table:
record_id, business_id, service_id_fk
When business owners sign up for my website they select the services their business offers using a simple form with checkboxes like this (I've only included two services to make things simple):
<form action ="insert_services.php">
<input type="checkbox" name="lang[ ]" >Behavior supports<br><br />
<input type="checkbox" name="lang[ ]" >Case Management<br><br />
</form>
This system is very straight forward and works fine but I'd like to use a similar form to allow businesses to edit the services they offer should they need to.
What I don't know how to do is how to dynamically generate the "edit form" based on the information contained in the database. To be clearer, let's say a business owner only checked off behavior supports when they originally signed up for the site.
So the corresponding record in the business_services_offered table would look like this:
record_id | business_id | service_id_fk
1 0000023 1
Oh and the services table looks like this:
service_id | service_name
1 Behavior supports
2 Case Management
Now the same owner decides they want to edit the services they offer...how would I dynamically show them a checkbox form with their services (in this case Behavior supports) already checked off.
Obviously, I'd sequel the database and join the two tables using services.service_id and business_services_offered.service_id_fk but during the while loop that produces the form, how would I cause behavior supports to already be checked off? Im guessing some sort of if statement but I'm not sure.
Any help would be greatly appreciated!
Here is the query I'm guessing would work
$query = "SELECT service_name, service_id, business_name" .
"FROM services, business_services_offered " .
"WHERE services.service_id = business_services_offered.service_id_fk";
$result = mysql_query($query)
or die(mysql_error());
And the while loop would look like this I guess:
while($row = mysql_fetch_array($result)){
$service_name = $row['service_name'];
echo "<form action ='edit_services.php'>" .
"<input type='checkbox' name='lang[ ]' >$service_name<br><br />" .
"<input type='checkbox' name='lang[ ]' >$service_name<br><br />" .
"</form>";
}
So again, how would I make sure that the checkbox for behavior supports was checked off.
Thanks!

Here is the form code and the jQuery
I will edit this answer in a minute with the separate PHP file to handle the DB query
<!-- Must include jQuery Library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
// Lets build the Services form
${'The Form'} = '<form name="editServicesForm" id="editServicesForm" action="edit_services.php" method="POST">
<h2>Services</h2>';
// query the service table
$query = mysql_query('SELECT * FROM `services`');
while($row = mysql_fetch_assoc($query)){
${'The Form'} .= '<label><input type="checkbox" name="CheckboxGroup[]" value="'.$row['service_id'].'" id="CheckboxGroup_0" />'.$row['service_name'].'</label><br />';
}
${'The Form'} = '</form>';
// add the form on the page where you need with this
?>
<?= ${'The Form'}; ?>
<!-- The jQuery to do the magic -->
<script type="text/javascript">
// waits for the document to finish loading so all the elements are there to manipulate
$(document).ready(function() {
// your users id to reference the services in the database query
var businessID = "1" // replace this with the users id
// Do a basic post to and external php file
$.post('post.api.php', {'api': 'getServices', 'business_id': businessID}, function(resp){
// parse the response and check the boxes
var obj = $.parseJSON(resp);
// loop through the services returned as active (checked)
$.each(obj, function(i, value){
// Check the checkbox with the corresponding value
$('input[type="checkbox"][value="'+value.service+'"]').attr('checked', true);
});
});
});
</script>
Contents op post.api.php
<?php
// only access this if there is value for api being posted to it
if(isset($_POST['api'])){
// only access this if $_POST['api'] = getServices
if($_POST['api'] == 'getServices'){
// Create and array to store the data
${'Response'} = array();
// Get the users id
${'Business ID'} = $_POST['business_id']; // you should clean this to avoid sql injection
// Iterator
${'Iterator'} = 0;
// Query your database and return the values of the services that you stored during registration.
$sql = "SELECT `service_id_fk` FROM `business_services_offered` WHERE `business_id` = '".${'Business ID'}."'"; // your WHERE statement should include the user id sent here in ${'User ID'}
$query = mysql_query($sql);
// Do your while loop with your query results
while($row = mysql_fetch_assoc($query)){
// store our service value
${'Response'}[${'Iterator'}]['service'] = $row['service_id_fk'];
// increment our iterator
${'Iterator'}++;
}
// return the json to the posting file
echo json_encode(${'Response'});
}
exit;
}
?>

Or you can do this:
${'Business ID'} = "1";
// query the service table
$query = mysql_query('SELECT `a`.`service_id`,`a`.`service_name`, `b`.`record_id` FROM `services` `a` LEFT JOIN `business_services_offered` `b` ON `b`.`service_id_fk` = `a`.`service_id` WHERE `b`.`business_id` = "'.${'Business ID'}.'"');
while($row = mysql_fetch_assoc($query)){
if($row['record_id'] != NULL){
$checked = ' checked="checked"';
} else {
$checked = '';
}
${'The Form'} .= '<label>
<input type="checkbox" name="CheckboxGroup[]" value="'.$row['service_id'].'" id="CheckboxGroup_0"'.$checked.' />'.$row['service_name'].'</label>
<br />';
}
${'The Form'} = '</form>';
echo ${'The Form'};

Related

How to GET URL parameters with PHP inside if(isset) statement for update form

I know you can get the URL parameters by using if(isset($_GET['id'])){
$id = $_GET['id']; and this works great, if I then close that 'if' statement and create a new one for the update/append-entry form on this same page (its the display page for each ind. database entry), I can't get the id that's been passed to the URL in this next if statement.
It is the if-statement that submits a new row ("condition") to my child table ("conditions") that has a foreign key that connects it to the parent table of health providers (the display page gets the provider's id from the search engine selection and displays their information, then has this "append entry" form at the bottom if someone wants to add a new health condition treated by this doctor.)
Everything works if I give it the right id number directly in my PHP ($id = 56), but not if I try to grab it from the URL INSIDE this second if statement ($id = $_GET['id'];).
if (isset($_GET['providerid']))
{
$providerid = $_GET['providerid']; /*THIS WORKS GREAT*/
$sql = "SELECT *, GROUP_CONCAT(DISTINCT conditions.condition_name
SEPARATOR ', ') AS all_conditions FROM `providers` INNER JOIN
`conditions` ON `providers`.`id` = `conditions`.`prov_id` WHERE
`prov_id`= $providerid";
$data = mysqli_query($connection, $sql) or die('error');
if(mysqli_num_rows($data) > 0){
$numresults = mysqli_num_rows($data);
while($row = mysqli_fetch_assoc($data)){
$providerid = $row['id'];
$providerfirstname = $row['provider_first_name'];
/*etc....*/
$conditions = $row['all_conditions'];
/*table displays provider info:*/
echo "<br><h1>".$providerfirstname." ".$providerlastname."
</h1>";
echo '<TABLE id="myTable" width="350px" border="1">';
//etc....(cutting out details)
echo '<tr><td><div id="myTable"><a href="#" id="addNew">Add+ .
</a></div></td><td><b>Conditions Treated:</b></td> .
<td>'.$conditions.'</td></tr>';
/*If user wants to add a new condition treated by provider that's
not listed:*/
echo '<tr><td></td><td>Add a new condition:</td><td><form
action="profilebackup.php" method="POST"><input type="text"
size="40" name="newcond" value="" placeholder="Add a Condition" /> .
<input type="submit" name="add1" value="Add"><br></td></tr>';
}
echo '</TABLE>';
}
else {
echo "0 results";
}
}
/*sends added conditions to child table, EVERYTHING WORKS EXCEPT
GETTING ID (WHICH WORKED ABOVE):*/
if(isset($_POST['add1'])){
$providerid = $_GET['providerid'];
$condition = mysqli_real_escape_string($connection,
$_POST['condition']);
$insql = "INSERT INTO `conditions` (condition_name, prov_id) VALUES
('$condition','$providerid')";
if(mysqli_query($connection, $insql)){
echo "Thank you! Your provider has successfully been submitted
to the database!";
}
else {
echo "Sorry, there was an problem submitting your provider to
the database." . $insql . mysqli_error($connection);
}
}
Everything works EXCEPT the GET function in the second if-statement. It returns error code that it does not have the correct foreign key constraint: "Cannot add or update a child row: a foreign key constraint fails" because it's not grabbing the id.
You are submitting a form via post to profilebackup.php but the handler for this form is trying to get the providerid. You need to send the providerid as a query string in the form's action if you want to be able to access it via $_GET.
<form method="post" action="profilebackup.php?providerid=<?php echo $providerid; ?>" ...
The proper way to do this would be to include a hidden input in the form and then access it via $_POST consistently.
<form method="post" action="profilebackup.php">
<input type="hidden" name="providerid" value="<?php echo $providerid; ?>">
...
</form>
And the handler code.
<?php
...
// Notice that now you can use $_POST consistently.
if (isset($_POST['add1'])) {
$providerid = $_POST['providerid'];
...
The problem lines in $sql statement where it take variable $providerid as string, not a php variable. $_GET works fine even if sending a different protocals such as POST, PUT, DELETE,... Something like this should work as expected:
$sql = "SELECT *, GROUP_CONCAT(DISTINCT conditions.condition_name
SEPARATOR ', ') AS all_conditions FROM `providers` INNER JOIN
`conditions` ON `providers`.`id` = `conditions`.`prov_id` WHERE
`prov_id`= " . $providerid ;

update checkboxes after submit

I am currently running into an issue, where I have this form consisting of checkboxes. I get the values of user preferences for the checkboxes from a database. Everything works great, and does what is supposed to do, however after I change and check some boxes and then hit the submit button, it will still show the old values to the form again. If I click again in the page again it will show the new values.
The code is shown below with comments.
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk
FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name
FROM categories
INNER JOIN portals on categories.portal_id=portals.portal_id
ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
<?php
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
if(isset($_POST['submit'])){
if(!empty($_POST['categories'])){
$cats= $_POST['categories'];
$result = mysqli_query($conn,$qry_del_usrcats); //delete all
for ($x = 0; $x < count($cats); $x++) {
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`)
VALUES ('".$_SESSION['user_id']."', '".$cats[$x]."');";
$result = mysqli_query($conn,$qry_add_usrcats);
}
echo "success";
}
elseif(empty($_POST['categories'])){ //if nothing is selected delete all
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
I am not sure what is causing to do that. Something is causing not to update the form after the submission. However, as i said everything works great meaning after i submit the values are stored and saved in the DB, but not shown/updated on the form. Let me know if you need any clarifications.
Thank you
Your procedural logic is backwards and you're doing a bunch of INSERT queries you don't need. As #sean said, change the order.
<?php
if(isset($_POST['submit'])){
if(isset($_POST['categories'])){
$cats= $_POST['categories'];
// don't do an INSERT for each category, build the values and do only one INSERT query with multiple values
$values = '';
for($x = 0; $x < count($cats); $x++) {
// add each value...
$values .= "('".$_SESSION['user_id']."', '".$cats[$x]."'),";
}
// trim the trailing apostrophe and add the values to the query
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`) VALUES ". rtrim($values,',');
$result = mysqli_query($conn,$qry_add_usrcats);
echo "success";
}
elseif(!isset($_POST['categories'])){ //if nothing is selected delete all
// you may want to put this query first, so if something is checked you delete all, so the db is clean and ready for the new data.
// and if nothing is checked, you're still deleting....
$qry_del_usrcats="DELETE FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name FROM categories INNER JOIN portals on categories.portal_id=portals.portal_id ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
Typically this occurs due to the order of your queries within the script.
If you want to show your updated results after submission, you should make your update or insert queries to be conditional, and have the script call itself. The order of your scripts is fine, but you just need to do the following:
Take this query:
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
and put it inside the if statement so it looks like this:
if (isset($_POST['submit'] {
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
$result = mysqli_query($conn,$qry_del_usrcats);
[along with the other updates you have]
}
Also, you will need to move this entire conditional above the form itself; typically any updates, inserts, or deletes should appear year the top of the form, and then call the selects afterward (outside of the conditional)

POST method and arrays

This is my first php project. I have created a website where users can upload their picture and then view the pictures of other users, one person at a time (similar to the old hotornot.com). The code below works as follows:
I create an array (called $allusers) containing all members except for the user who is currently logged in ($user).
I create an array (called $usersiviewed) of all members who $user has previously either liked (stored in the likeprofile table) or disliked (stored in the dislikeprofile table). The first column of likeprofile and dislikeprofile has the name of users who did the liking/disliking, second column contains the name of the member they liked/disliked.
I use the array_diff to strip out $usersiviewed from $allusers. This is the list of users who $user can view (ie, people they have not already liked or disliked in the past).
Now the problem is when I click the like button, it updates the likeprofile table with the name of the NEXT person in the array (i.e., not the person who's picture I am currently looking at but person who's picture appears next). Additionally, if I refresh the current page, the person who's profile appears on the current page automatically gets 'liked' by me. I would really appreciate any advice on this.
<?php
// viewprofiles.php
include_once("header.php");
echo $user.' is currently logged in<br><br>';
echo <<<_END
<form method="post" action="viewprofiles.php"><pre>
<input type="submit" name ="choice" value="LIKE" />
<input type="submit" name ="choice" value="NEXT PROFILE" />
</pre></form>
_END;
$allusers = array();
//Create the $allusers array, comprised of all users except me
$result = queryMysql("SELECT * FROM members");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
if ($row[0] == $user) continue;
$allusers[$j] = $row[0];
}
//Create the $i_like_these_users array, comprised of all users i liked
$result = queryMysql("SELECT * FROM likeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_like_these_users[$j] = $row[1];
}
//Create the $i_dislike_these_users array, comprised of all users i disliked
$result = queryMysql("SELECT * FROM dislikeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_dislike_these_users[$j] = $row[1];
}
//Create the $usersiviewed array, comprised of all users i have either liked or disliked
if (is_array($i_like_these_users) && is_array($i_dislike_these_users))
{
$usersiviewed = array_merge($i_like_these_users,$i_dislike_these_users);
}
elseif(is_array($i_like_these_users))
{
$usersiviewed = $i_like_these_users;
}
else
{
$usersiviewed = $i_dislike_these_users;
}
// this removes from the array $allusers (i.e., profiles i can view) all $usersviewed (i.e., all the profiles i have already either liked/disliked)
if (is_array($usersiviewed))
{
$peopleicanview = array_diff($allusers, $usersiviewed);
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
else {
$peopleicanview = $allusers;
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
$current_user_profile = $peopleicanview[0];
echo 'check out '.$current_user_profile.'s picture <br />';
if (file_exists("$current_user_profile.jpg"))
{echo "<img src='$current_user_profile.jpg' align='left' />";}
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['choice']) && $_POST['choice'] == 'LIKE')
{
$ilike = $current_user_profile;
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$ilike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['choice']) && $_POST['choice'] == 'NEXT PROFILE')
{
$idontlike = $current_user_profile;
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$idontlike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
?>
Because when you refresh page it sends previus value of
Form again...and problem when u like a user it being liked next user.. There there is something in yor for loop while fetching row ...insted of for loop try once while loop ...i hope it will solve ur problem
You are calculating the $iLike variable with the currently loaded user and then updating the database with that user.
You should probably change your application logic a bit:
pass the user ID of the user you liked or did not like as a POST parameter in addition to the like/didn't like variable
move the form processing logic to the top of your page (or better yet separate out your form processing from HTML display)
Also, it's best not to use the mysql_* extensions in PHP. Use mysqli or PDO.
Try to make two different forms. One with "LIKE", another with "NEXT" to avoid liking from the same form
When you submit your form - your page refreshes, so in string $current_user_profile = $peopleicanview[0]; array $peopleicanview doesn't have user from previuos page (before submitting) you have to attach it, e.g. in hidden field
<form method="post" action="viewprofiles.php">
<input type="hidden" name="current_user" value="$current_user_profile" />
<input type="submit" name ="choice" value="like" />
</form>
<form method="post" action="viewprofiles.php">
<input type="submit" name ="go" value="next" />
</form>
and INSERT it later
"INSERT INTO likeprofile VALUES" . "('$user', '".$_POST['current_user']."')"
ps remove <pre> from your form
Lets start by simplifying and organizing the code.
<?php
// viewprofiles.php
include_once("header.php");
//if form is sent, process the vote.
//Do this first so that the user voted on wont be in results later(view same user again)
//use the user from hidden form field, see below
$userToVoteOn = isset($_POST['user-to-vote-on']) ? $_POST['user-to-vote-on'] : '';
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['like']))
{
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['dislike']))
{
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
//now we can create array of available users.
$currentProfileUser = array();
//Create the $currentProfileUser array,contains data for next user.
//join the 2 other tables here to save php processing later.
$result = queryMysql("SELECT `user` FROM `members`
WHERE `user` NOT IN(SELECT * FROM `likeprofile` WHERE user='$user')
AND `user` NOT IN(SELECT * FROM `dislikeprofile` WHERE user='$user')
and `user` <> '$user'
LIMIT 1");
//no need for a counter or loop, you only need the first result.
if(mysql_num_rows > 0)
{
$row = mysql_fetch_assoc($result);
$current_user_profile = $row['user'];
}
else
$current_user_profile = false;
echo $user.' is currently logged in<br><br>';
//make sure you have a user
if($current_user_profile !== false): ?>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="like" value="LIKE" />
</form>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="dislike" value="NEXT PROFILE" />
</form>
check out <?=$current_user_profile?>'s picture <br />
<?php if (file_exists("$current_user_profile.jpg")): ?>
<img src='<?=$current_user_profile.jpg?>' align='left' />
<?php endif; //end check if image exists ?>
<?php else: //no users found ?>
Sorry, there are no new users to view
<?php endif; //end check if users exists. ?>
You'll notice I changed the code a lot. The order you were checking the vote was the main reason for the issue. But over complicating the code makes it very difficult to see what's happening and why. Make an effort to organize your code in the order you expect them to run rather a vote is cast or not, I also made an effort to separate the markup from the logic. This makes for less of a mess of code to dig through when looking for the bug.
I also used sub queries in the original query to avoid a bunch of unnecessary php code. You could easily have used JOIN with the same outcome, but I think this is a clearer representation of what's happening. Also please use mysqli instead of the deprecaded mysql in the future, and be aware of SQL injection attacks and makes use of real_escape_string at the very least.
Hope it works out for you. Also I didn't test this code. Might be a few errors.

select id from the select gender dropdown list

I have a dropdown list of gender. I am getting the values from my table 'candidate' and in this table i have a field which is actually a foreign key to another table.
The field is gender_code_cde, and the table name is gender_code. Now gender_code contains 2 rows. and id and a description. Its structure is like:
1->Male
2->Female
Its being displayed in dropdown list. but I want to get the id 1 if male is selected and id 2 if female is selected. My code is below:
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
I am working in codeIgniter.
// this will alert value of dropdown whenever it will change
<script>
function getvalue(val)
{
alert(val);
}
</script>
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER" id="Gender" onchange="getvalue(this.value)">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
In Javascript, you can get the value with native JS.
var e = document.getElementById("give-the-select-element-an-id");
var gender_cde = e.options[e.selectedIndex].value;
If, you want it back at the server, it will come in to PHP as $_GET['GENDER'] or $_POST['GENDER'] depending on if the form does a POST or a GET request.
If you are submitting a (POST) form and this is inside that form you can access the the value (id) from CodeIgniter's $_POST wrapper: $this->input->post('GENDER');. I don't use CodeIgniter so I could be wrong, but it will be located in your $_POST array from PHP.
If you just want to replicate the variable somewhere on the page you can just echo it. Or set via js/jQuery with document.getElementById('#something').value = value; or jQuery('#something').html(value);.
You should also change the following:
use a foreach in place of your while:
foreach ($query as $row) {
echo $row['gender_x'] . $row['gender_y'];
}
use the CodeIgniter SQL wrapper instead of depreciated PHP functions. The query part is $this->db->query('SELECT statement goes here');. You should look at your CodeIgniters' version documentation for a more in depth explanation.
EDIT: To make it a bit more clear, an example:
$query = $this->db->query('SELECT * FROM gender_code');
foreach ($query->result() as $row) {
echo '<option value="' . $row->gender_cde . '">' . $row->geneder_dsc . '</option>';
}
This is assuming you have setup the previous calls in CodeIgniter. Please see http://ellislab.com/codeigniter/user-guide/database/examples.html and you may wish to read http://ellislab.com/codeigniter/user-guide/

Processing a form created by dynamic php/mySql Setup

I run a script to create an order form, this is just a really small sample. I'm not so good with PHP and dynamic forms. It pulls data from mysql database.
<td>
<h3>Round Cuts</h3>
<?php while($row = mysql_fetch_array($round_cuts)){
$round_box_value = #$row["meat_names"];
$round_box_value_name = #$row["meat_names"];
echo " <input type=\"checkbox\" name=\"round_box_value\" value=\"$round_box_value_name\"> $round_box_value_name";
echo "<br>";
}?>
</td>
I've ever really only built basic contact forms, how could I process a dynamic form like this. If all else fails I would just take all the possible elements and program this like it was a not dynamic. There must be a better way though.
Even a link to a website would be helpful. I've been searching for a solution. Thanks.
I'll assume your table as a primary key of id
Start off with a minor change to your checkboxes:
<?php
while($row = mysql_fetch_array($round_cuts)){
echo sprintf('<label><input type="checkbox" name="round_box_value[]" value="%s"> %s</label><br>', $row['id'], $row['meat_names']);
}
?>
The name now has an [] at the end to tell php it's an array of values + I've wrapped the checkbox in a label for convenience.
Then when you process the form, you can simply iterate through round_box_value like so
<?php
foreach ($_POST['round_box_value'] as $id) {
// $id is the table reference from your previous table
}
// or query all the rows selected
$ids = array_map('intval', $_POST['round_box_value']); // "basic" sql injection handler
$sql = "SELECT * FROM table WHERE id IN (".implode(",", $ids).")";
should produce something like:
SELECT * FROM table WHERE id IN (2,5,7)

Categories