Jump to content

[SOLVED] Inserting a check in checkbox from array value


jmr3460

Recommended Posts

Hello all,

I have a bit of code that works for a select option box, but does not work for my checkboxes. I need multiple selections on this code and I really don't like the look of multiple select option box. The code does insert the word checked on the first value in the array, but only that one box even if there are multiple values brought from the database. This works good:

<select name=\"time\">" .
		$times = array("12AM" => "0:00", "1AM" => "1:00", "2AM" => "2:00", "3AM" => "3:00", "4AM" => "4:00", "5AM" => "5:00", "6AM" => "6:00",
"7AM" => "7:00", "8AM" => "8:00", "9AM" => "9:00", "10AM" => "10:00", "11AM" => "11:00", "12PM" => "12:00", "1PM" => "13:00",
"2PM" => "14:00", "3PM" => "15:00", "4PM" => "16:00", "5PM" => "17:00", "6PM" => "18:00", "7PM" => "19:00", "8PM" => "20:00",
"9PM" => "21:00", "10PM" => "22:00", "11PM" => "23:00");
foreach ($times as $k => $v)
{
if ($v == $time){
	$select = " selected";
}
else
{
	$select = " ";
}

echo "<option value=\"" .$v . "\"" . $select . ">" . $k . "</option>";
}
echo "</select>";

Why doesn't this:

$formats = array("Discussion" => "Discussion,", "Basic Text Study" => "Basic Text Study,", "It Works Study" => "It Works Study,",
							"IP Study" => "IP Study,", "Topic" => "Topic,", "Step Study" => "Step Study,", "Tradition Study" => "Tradition Study,",
							"Candlelight" => "Candlelight,", "Speaker" => "Speaker,", "Birthday" => "Birthday,", "Men" => "Men,",
							"Women" => "Women,", "Varies" => "Varies,", "Other" => "Other,");
		echo "<table>";
	//set 3 to 4 of you want 4 columns. Set it to 5 if you want 5, etc
	$numcols = 3; // how many columns to display
	$numcolsprinted = 0; // no of columns so far
	//Query for display.php
	foreach($formats as $k => $v)
	{
		if ($numcolsprinted == $numcols)
		{
		echo "</tr>\n<tr>\n";
		$numcolsprinted = 0;
		}
		if ($v == $format){
			$select = " checked";
		}
		else
		{
			$select = " ";
		}
	// output row from foreach
	echo "<td><input type=\"checkbox\" name=\"format[]\" value=\"" . $v . "\"" . $select . ">" . $k . "</td>\n";
		// bump up row counter
		$numcolsprinted++;
		} // end while loop
		$colstobalance = $numcols - $numcolsprinted;
		for ($i=1; $i<=$colstobalance; $i++) {
		echo "<td></td>\n";
		}

Thanks for any help.

Link to comment
Share on other sites

How are you storing these values in your database? Are they being stored as an array? Or are you storing each value of $formats in its own row? Also, (for your purposes) a key-value system isn't exactly useful. Just stick to using values:

<?php
$formats = array("Discussion,", "Basic Text Study,", "It Works Study,", "IP Study,", "Topic,", ...);
?>

Link to comment
Share on other sites

So you're storing them in separate rows as a string? Well, if that's the case, you have to either store the values in the database as an array (use serialize and unserialize to store arrays in database fields) or you can use a while loop to go through all of the rows retrieved by your SQL-Query and store them in an array that way (an example):

 

<?php
    $query = pgsql_query("SELECT `value` FROM `table` WHERE ...");
    $results = array();
    while($row = pgsql_fetch_assoc($query)){
        $results[] = $row['value'];
    }
?>

Link to comment
Share on other sites

Try removing the comma from the array-values in $formats. When you explode a string into an array, it completely removes the 'glue' that's used to hold the string together.

 

<?php
    $str = '127,0,0,1';
    $array = explode(',', $str);
    print_r($array);
?>

 

The array values would then look like:

Array (
          [0] => 127
          [1] => 0
          [2] => 0
          [3] => 1 )

As you can see, there are NO commas to be found in the contents of the array.

Link to comment
Share on other sites

Well, if $formatted is an array of values from your database, then you aren't comparing correctly. You can't just compare a string and an array. You have to use the in_array function:

<?php
    if(in_array($v, $formatted)) $select = ' checked';
    else $select = '';
?>

 

That should work. There are other alternatives if that doesn't work (but I believe this is the easiest as it won't require you to do a whole lot of restructuring to your loops as the other method would).

Link to comment
Share on other sites

I guess I will need to do some more research tomorrow I can't get it to work. What kind of restructuring would I need to do. This is an example of my data coming from my database.(Discussion, Men, Speaker,) I am trying to split into an array and compare with $formats.

Link to comment
Share on other sites

Does the $formatted array have any elements (values) in it?

 

If you're not sure, do this:

 

echo print_r($formatted);

 

Paste that into your script where you'll be able to see it on the screen. This will show you exactly what is inside the array. If you see nothing, it probably means the $formatted array is empty. Which in that case would mean that you're either not exploding them correctly, or you have nothing stored in your database column.

 

EDIT: If you have spaces after your commas in your database values, then you also need to account for that when you explode them into an array.

    <?php
        $str = "Discussion, Men, Speaker";
        $array1 = explode(",", $str);
        $array2 = explode(", ", $str);
    ?>

 

There will not produce exactly the same results. $array1 will look like

array("Discussion", " Men", " Speaker");

 

Notice the spaces before the last two elements. To PHP, these are completely different strings compared to the elements of $array2

array("Discussion", "Men", "Speaker");

 

I hope this is clear enough. If not, just say so.

 

In short: try explode(", ", $your_database_string); (if you aren't already).

Link to comment
Share on other sites

Thanks for that bit of information. It now appears that I am only getting the first value of my string in my explode(', ' $string).  My string looks like this

(Discussion, Men, Speaker,) and when I print_r(explode($string)) all I get is (Discussion,). Why is this?

Link to comment
Share on other sites

OK sorry so long for reply.

My first bit of code that applies is

<?php
echo "<h1 style=\"text-align:center;\">Update Meeting for <span style=\"color:red;\">" . $groupname . "</span></h1>";
$sql_meeting = "SELECT * FROM meeting WHERE meeting_id = '$meeting_id' AND del = 0";
$query_meeting = mysql_query($sql_meeting) or trigger_error(mysql_error());
$result_meeting = mysql_fetch_array($query_meeting);
$day = $result_meeting['day'];
$time = $result_meeting['time'];
$open = $result_meeting['open'];
$format = $result_meeting['format'];
$form = explode(', ', $format);

$format when I print_r($format);

returns a value of

Discussion, IP Study, Tradition Study, Birthday, Varies,

 

When I display it I substr() the last , out for presentation purposes.

This value comes from an array from a checkbox name=format[].

I have done this with this code:

	$formats = $_POST['format'];
	$format = implode(' ',$formats);

I have created an array called $formats.

$formats = array("Discussion" => "Discussion,", "Basic Text Study" => "Basic Text Study,", "It Works Study" => "It Works Study,","IP Study" => "IP Study,", "Topic" => "Topic,", "Step Study" => "Step Study,", "Tradition Study" => "Tradition Study,",
"Candlelight" => "Candlelight,", "Speaker" => "Speaker,", "Birthday" => "Birthday,", "Men" => "Men,","Women" => "Women,", "Varies" => "Varies,", "Other" => "Other,");

I then use a foreach loop:

	foreach($formats as $k => $v)
	{
		if (in_array($formats, $formatted)){
			$select = " checked";
		}
		else
		{
		$select = " ";
		}
	// output row from foreach
	echo "<td><input type=\"checkbox\" name=\"format[]\" value=\"" . $v . "\"" . $select . ">" . $k . "</td>\n";
                                }

My purpose is to put a check in the box that has a value from my original string. This is the last script in my admin folder for this meeting select page which is one of over 15 scripts and forms or so that adds and edits information in a meeting database. This check in the checkbox thing is something I can do without for now but eventually I am going to need them their because other members will be editing this information and I really need it to be as simple as possible.

Link to comment
Share on other sites

Okay, a few things that can changed:

 

1) Remove the commas and array-keys from your array values in $formats (believe me, they aren't necessary) like so:

$formats = array("Discussion", "Basic Text Study", "It Works Study", "IP Study", "Topic", "Step Study", "Tradition Study", "Candlelight", "Speaker", "Birthday", "Men", "Women", "Varies", "Other");

 

2) I noticed that you implode your arrays with a space and explode them with a comma-and-space. Just stick to one type of 'adhesive' it makes things quite a bit easier.

<?php
// taking the formats from the database
$form = explode(', ', $result_meeting['format']);

// when putting the formats into the database
$format = $_POST['format'];
$format = implode(', ', $formats);
?>

3) Your foreach loop will now look like this (if you use the 'cleaner' array I provided in #1):

<?php
foreach($formats as $format)
	{
		if (in_array($format, $formatted)){
			$select = " checked";
		}
		else
		{
			$select = " ";
		}
		// output row from foreach
		echo "<td><input type=\"checkbox\" name=\"format[]\" value=\"" . $format . "\"" . $select . ">" . $format . "</td>\n";
	}
?>

[/code]

Link to comment
Share on other sites

I wanted to get back with Goldeneye and tell you thanks for your help and patience. I did exactly what you said and my check boxes are working.  One of my main issues were the spaces after the commas. I hope to be able to help people with PHP some day. Thanks and I am going to mark this topic solved.

 

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.