Question

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!

Was it helpful?

Solution

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;
}
?>

OTHER TIPS

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'};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top