Multiple checkboxes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
freemojorisin
Forum Newbie
Posts: 7
Joined: Fri Mar 11, 2005 11:34 am

Multiple checkboxes

Post by freemojorisin »

Hi..

I'm doing a form where you can edit information about websites...in this form we have the possibility to select different categories for only one website but the problem is that when I edit the information for the site, it only takes one value from all the checkboxes that I choose and then in the database only appears one value.

I need some help about how to get the values from the checkboxes that I choose and store it in the database.

Here is the code...

Code: Select all

<?
			foreach($sitios as $sitio)	{
			?>
                      <b><font color="#000000">
                      <input name="N<? echo $sitio["id_sitio"]?>" type="text" id="N<? echo $sitio["id_sitio"]?>" value="<?echo $sitio["nombre"]?>" size="40" maxlength="100">
                      </font></b></td>
                  </tr>
                  <tr valign="top"> 
                    <td><b><font color="#000000">Categor&iacute;a</font></b> </td>
                    <td> 
					 <?
						foreach($categorias as $categoria)	{
						foreach($catego as $categ) {
						?>
                      <input name="C<? echo $sitio["id_sitio"]?>" value="<? echo $categ["id_categoria"]?>"  <? if($sitio["categoria"] == $categ["id_categoria"]){?>checked <? }?>type="checkbox">
                      <? echo $categ["nombre"]?><br>
                        <?
						}}
						?>                  </tr>
                  <tr valign="top">
                    <td><b><font color="#000000">URL</font></b></td>
                    <td><input name="U<? echo $sitio["id_sitio"]?>" type="text" id="U<? echo $sitio["id_sitio"]?>" value="<?echo $sitio["url"]?>" size="40" maxlength="200"></td>
                  </tr>
                  <tr valign="top">
                    <td><b><font color="#000000">Descripci&oacute;n</font></b></td>
                    <td><textarea name="R<? echo $sitio["id_sitio"]?>" cols="30" rows="5" id="textarea"><?echo $sitio["descripcion"]?></textarea></td>
                  </tr>
                  <tr valign="top">
                    <td><b><font color="#000000">Palabras Clave</font></b></td>
                    <td><textarea name="P<? echo $sitio["id_sitio"]?>" cols="30" rows="5" id="textarea2"><?echo $sitio["palabras"]?></textarea></td>
                  </tr>
                  <?
			}
			?>
Thanks!!


feyd | Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

the checkbox name should be an array.. such as 'C23[]'
freemojorisin
Forum Newbie
Posts: 7
Joined: Fri Mar 11, 2005 11:34 am

Post by freemojorisin »

I don't understand what you mean...how can I do that??
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

are your checkbox names dynamically assigned? It looks as though they are given the fact they are in that foreach loop. If that's the case, you need to make sure you're grabbing the correctly named checkbox for its value.

If you have more than one checkbox with the same name, then you'll need to do exactly what Feyd suggested and use an array so you can pass multiple values for the same checkbox name:

example:

Code: Select all

<form action="action.php" method="post">
<input type="checkbox" name="thischeck[]" value="1">
<input type="checkbox" name="thischeck[]" value="2">
<input type="checkbox" name="thischeck[]" value="3">
then on your action.php page you need to use the array to do stuff with the thischeck form field.

example:

Code: Select all

$checkvals = implode(",",$_POST['thischeck']);
or you could loop over all of the values similarly to wha tyou're doign on your form page itself with a foreach loop.

Burr
freemojorisin
Forum Newbie
Posts: 7
Joined: Fri Mar 11, 2005 11:34 am

Post by freemojorisin »

the idea is that I can choose more than one checkbox when one site belongs to more than one category but I don't know how to get these values, separated by comma and update the database.

Can you help me with that??
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

as I asked in my last post: are these checkboxes goign to share the same name?

if so, then you need to do exactly as Feyd suggested and the code sample that I posted (put it into an array).

then on your action page you'd strip out the values of that array for your sql.

using the implode() function as I outlined will separate the values into a comma separated list exactly like you need.

If you're not going to use the same name for multiple checkboxes, then you'll have to create your comma separated list by obtaining the values from all of your checkboxes.

you can determine if a checkbox is ticked by using the isset function on your action page.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

that's what our suggestion(s) do/does..

Here's an easier to work with way:

Code: Select all

$i = 0;
foreach($sitios as $sitio)
{
  echo &lt;&lt;&lt;STOP
  &lt;span style=&quote;color:black;font-weight:bold&quote;&gt;&lt;input name=&quote;sitios&#1111;{$i}]&#1111;nombre]&quote; value=&quote;{$sitio&#1111;'nombre']}&quote; size=&quote;40&quote; maxlength=&quote;100&quote; /&gt;&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr style=&quote;vertical-align:top&quote;&gt;
  &lt;td&gt;&lt;span style=&quote;color:black;font-weight:bold&quote;&gt;Categor&amp;iacute;a&lt;/span&gt;&lt;/td&gt;
  &lt;td&gt;
STOP;

  $j = 0;
  foreach($categorias as $categoria)
  {
    $k = 0;
    foreach($catego as $categ)
    {
      echo '    &lt;input name=&quote;sitios&#1111;' . $i . ']&#1111;categoria]&#1111;' . $j . ':' . $k . ']&quote; value=&quote;' . $categ&#1111;'id_categoria'] . '&quote;' . ($sitio&#1111;'categoria'] == $categ&#1111;'id_categoria'] ? ' checked=&quote;checked&quote;' : '') . ' type=&quote;checkbox&quote; /&gt; ' . $categ&#1111;'nombre'] . '&lt;br /&gt;' . &quote;\n&quote;;
      $k++;
    }
    $j++;
  } // I don't see the point of these two loops, $categoria isn't used... :-/

  echo &lt;&lt;&lt;STOP
      &lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr style=&quote;vertical-align: top&quote;&gt;
      &lt;td&gt;&lt;span style=&quote;color:black;font-weight:bold&quote;&gt;URL&lt;/span&gt;&lt;/td&gt;
      &lt;td&gt;&lt;input name=&quote;sitios&#1111;{$i}]&#1111;url]&quote; type=&quote;text&quote; value=&quote;{$sitio&#1111;'url']}&quote; size=&quote;40&quote; maxlength=&quote;200&quote; /&gt;&lt;/td&gt;
freemojorisin
Forum Newbie
Posts: 7
Joined: Fri Mar 11, 2005 11:34 am

Post by freemojorisin »

but the problem is that I don't have an action page for the form...the update to the database is on the same page so what can I do??
freemojorisin
Forum Newbie
Posts: 7
Joined: Fri Mar 11, 2005 11:34 am

Post by freemojorisin »

let me show you the code for the page

Code: Select all

<?php
require("lib_php/bd.class.php");
session_start();
$cat=$_GET["cat"];

if($_SESSION["usuario"] == "")	{
	header("Location: entrar.php");
}

$dele = new BaseDatos;
$dele->connect();
$cons = new BaseDatos;
$cons->connect();

if($_POST["accion"] == "editar")	{
	$sql = "Select id_sitio,email from sitios_utiles where id_sitio=" . $GLOBALS["cat"];
	$res = $cons->query($sql);
	while($sitioc = $cons->fetch_row($res))	{
			$sql = "Update sitios_utiles Set descripcion='".$_POST["R".$sitioc["id_sitio"]]."',nombre='".$_POST["N".$sitioc["id_sitio"]]."',url='".$_POST["U".$sitioc["id_sitio"]]."',palabras='".$_POST["P".$sitioc["id_sitio"]]."',categoria=".$_POST["C".$sitioc["id_sitio"]].",calificacion=".$_POST["V".$sitioc["id_sitio"]]." where id_sitio=".$sitioc["id_sitio"];
			echo $sql. "-----<br>";
			$dele->query($sql);
	}
}
//TRAE LAS SECCIONES PERMITIDAS PARA EL USUARIO
$secciones = array();
$consulta = new BaseDatos;
$consulta->connect();
$sql = "Select s.nombre,s.link from seccion s,acceso a where a.seccion=s.id_seccion and a.login='".$_SESSION["usuario"]."' ORDER BY s.nombre ";
$res = $consulta->query($sql);
while($item = $consulta->fetch_row($res))	{
	array_push($secciones,$item);
}
//TRAE EL SITIOS ACTUAL
$sitios = array();
$conssit = new BaseDatos;
$conssit->connect();
$sql = "Select * from sitios_utiles where id_sitio=" . $GLOBALS["cat"];
$res = $conssit->query($sql);
while($item = $conssit->fetch_row($res))	{
	array_push($sitios,$item);
}
//TRAE TODOS LOS SITIOS UTILES ACTUALES
$sit = array();
$conssit = new BaseDatos;
$conssit->connect();
$sql = "Select * from sitios_utiles";
$res = $conssit->query($sql);
while($item = $conssit->fetch_row($res))	{
	array_push($sit,$item);
}

//TRAE LAS CATEGORIAS ACTUALES
$categorias = array();
$conssit = new BaseDatos;
$conssit->connect();
$sql = "SELECT * FROM sitios_utiles INNER JOIN categorias ON sitios_utiles.categoria = categorias.id_categoria WHERE sitios_utiles.id_sitio=" . $GLOBALS["cat"];
$res = $conssit->query($sql);
while($item = $conssit->fetch_row($res))	{
	array_push($categorias,$item);
}
//TRAE TODAS LAS CATEGORIAS 
$catego = array();
$conssit = new BaseDatos;
$conssit->connect();
$sql = "Select * from categorias order by nombre";
$res = $conssit->query($sql);
while($item = $conssit->fetch_row($res))	{
	array_push($catego,$item);
}

?>
<html>
<head>
<title>Imagine S.A. - imagine.com.co - Su aliado efectivo para Internet</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="../textos.css" type="text/css">
<script language="JavaScript">
<!--


var tipTimer;

function mOvr(src) {
    if (!src.contains(event.fromElement)) {
	  src.style.cursor = 'hand';
	}
  }

//-->//-->
</script>
<script language="JavaScript">
<!--

<!--
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);
// -->
//-->
</script>
</head>
<body bgcolor="#FFFFFF" text="#000000" background="../nopierda/images/camara_web_fondo_internet.gif" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<a name="arriba"></a> 
<table width="100%" border="0" cellspacing="0">
  <tr> 
    <td align="left" valign="top" height="693"> <table width="739" border="0" cellspacing="0" height="54">
        <tr> 
          <td height="53" align="left" valign="middle" background="../nopierda/images/camara_web_chat_imagenes_1.gif" width="332">&nbsp; 
          </td>
          <td height="53" align="left" valign="middle" background="../nopierda/images/camara_web_chat_imagenes_2.gif" width="403">&nbsp;</td>
        </tr>
      </table>
      <table width="684" border="0" cellspacing="0" height="34">
        <tr> 
          <td height="15" width="258" align="center" valign="middle"><b>Un socio 
            efectivo para Internet</b></td>
          <td height="15" width="422" background="../nopierda/images/camara_web_entradas_web.gif" align="left" valign="middle">&nbsp; 
          </td>
        </tr>
      </table>
      <table width="100%" border="0" cellspacing="0">
        <tr> 
          <td width="120" rowspan="2" align="center" valign="top" background="../nopierda/images/camara_web_chat_colombia.gif"> 
            <br> <br> 
            <table width="90%" border="1" cellspacing="0" cellpadding="0">
              <?
			foreach($secciones as $seccion)	{
			?>
              <tr> 
                <td> <p><a href="<? echo $seccion["link"]?>">&nbsp;<? echo $seccion["nombre"]?></a></p></td>
              </tr>
              <?
			}
			?>
              <tr> 
                <td><p><a href="salir.php">&nbsp;Salir</a></p></td>
              </tr>
            </table>
            <br>
          </td>
          <td class="mytext2" valign="top" align="center"> 
            <form name="form1" method="post" action="">
              <div align="center"><font color="#000000"><b>Sitios Utiles - Edici&oacute;n<br>
                <br>
                <br>
              </b></font> </div>
              <div align="left"> 
                <table width="50%" border="1" align="center" cellpadding="6" cellspacing="0">
                  <tr> 
                    <td> 
                      <div align="left"><b><font color="#000000">Nombre 
                        sitio</font></b></div></td>
                    <td>
            <?
			foreach($sitios as $sitio)	{
			?>
                      <b><font color="#000000">
                      <input name="N<? echo $sitio["id_sitio"]?>" type="text" id="N<? echo $sitio["id_sitio"]?>" value="<?echo $sitio["nombre"]?>" size="40" maxlength="100">
                      </font></b></td>
                  </tr>
                  <tr valign="top"> 
                    <td><b><font color="#000000">Categor&iacute;a</font></b> </td>
                    <td> 
					 <?
						foreach($categorias as $categoria)	{
						foreach($catego as $categ) {
						?>
                      <input name="C<? echo $sitio["id_sitio"]?>[]" value="<? echo $categ["id_categoria"]?>"  <? if($sitio["categoria"] == $categ["id_categoria"]){?>checked <? }?>type="checkbox">
                      <? echo $categ["nombre"]?><br>
					   <?
					   $checkvals = implode(",",$_POST['C<? echo $sitio["id_sitio"]?>']);
						}}
						?>                  </tr>
                  <tr valign="top">
                    <td><b><font color="#000000">URL</font></b></td>
                    <td><input name="U<? echo $sitio["id_sitio"]?>" type="text" id="U<? echo $sitio["id_sitio"]?>" value="<?echo $sitio["url"]?>" size="40" maxlength="200"></td>
                  </tr>
                  <tr valign="top">
                    <td><b><font color="#000000">Descripci&oacute;n</font></b></td>
                    <td><textarea name="R<? echo $sitio["id_sitio"]?>" cols="30" rows="5" id="textarea"><?echo $sitio["descripcion"]?></textarea></td>
                  </tr>
                  <tr valign="top">
                    <td><b><font color="#000000">Palabras Clave</font></b></td>
                    <td><textarea name="P<? echo $sitio["id_sitio"]?>" cols="30" rows="5" id="textarea2"><?echo $sitio["palabras"]?></textarea></td>
                  </tr>
                  <tr valign="top">
                    <td><b><font color="#000000">Calificaci&oacute;n</font></b></td>
                    <td><table width="71">
                      <tr>
                        <td><label>
                          <input type="radio" name="V<? echo $sitio["id_sitio"]?>" value="1">
                          1</label></td>
                      </tr>
                      <tr>
                        <td><label>
                          <input type="radio" name="V<? echo $sitio["id_sitio"]?>" value="2">
                          2</label></td>
                      </tr>
                      <tr>
                        <td><label>
                          <input type="radio" name="V<? echo $sitio["id_sitio"]?>" value="3">
                          3</label></td>
                      </tr>
                      <tr>
                        <td><label>
                          <input type="radio" name="V<? echo $sitio["id_sitio"]?>" value="4">
                          4</label></td>
                      </tr>
                      <tr>
                        <td><label>
                          <input type="radio" name="V<? echo $sitio["id_sitio"]?>" value="5">
                          5</label></td>
                      </tr>
                    </table></td>
                  </tr>
                  <?
			}
			?>
                </table>
                <div align="center"><font color="#000000"><b> <br>
                  <br>
                  </b> &nbsp;&nbsp;&nbsp;&nbsp; 
                  <input type="hidden" name="accion" value="">
                  <input type="submit" name="editar" value="Editar" class="botones" onClick="document.all.accion.value='editar'">
                </font></div>
              </div>
            </form>
            <div align="left"><font color="#000000"><b><br>
              </b></font> <br>
              <br>
            </div>
            <font color="#000000"><b> </b></font></td>
        </tr>
        <tr> 
          <td class="mytext2" valign="top" align="center"> 
            <table width="459" border="0" cellspacing="2" align="center">
              <tr> 
                <td width="9">&nbsp;</td>
                <td width="118" class="internas">&nbsp;</td>
                <td width="178" class="internas" align="center">&nbsp;</td>
                <td width="136" class="internas">&nbsp;</td>
              </tr>
            </table></td>
        </tr>
        <tr> 
          <td valign="top" align="left">&nbsp;</td>
          <td class="mytext2">&nbsp;</td>
        </tr>
      </table></td>
  </tr>
</table>
</body>
</html>

feyd | Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

put some kind of check at the top of your page to determine if post values have been sent:

example:

Code: Select all

if(isset($_POST['yourvar'])){
  //do stuff here
}
AGISB
Forum Contributor
Posts: 422
Joined: Fri Jul 09, 2004 1:23 am

Post by AGISB »

This site got a nice tutorial section with a perfect tutorial on CheckBoxes and Radio Buttons.
Post Reply