Jump to content


Photo

php one to many insert with checkboxes? - SOLVED


  • Please log in to reply
7 replies to this topic

#1 john_6767

john_6767
  • Members
  • PipPipPip
  • Advanced Member
  • 99 posts

Posted 08 October 2006 - 03:30 AM

hey guys, i've been trying to find out how to do this for a while with no success although i have seen it in as common practise in many places so it can't be too hard..

basically i have an item (in my case bouncy balls) and this item can have many of another thing related to it (in my case sizes).

I have set up a very simple test site to try get this working and have attatched it hoping that someone can show me where i have gone wrong..

I have included the simple database i made as an sql export also so its easy to set up and see what i have done if someone has the time, but any help with links to information or snippets of code would be much appreciated.

[attachment deleted by admin]

#2 tomfmason

tomfmason
  • Staff Alumni
  • Advanced Member
  • 1,696 posts
  • Locationstealing your wifi

Posted 08 October 2006 - 03:54 AM

You should post the code and not just upload it. Most people will not download that.

Traveling East in search of instruction, and West to propagate the knowledge I have had gained.

current projects: pokersource

My Blog | My Pastebin | PHP Validation class | Backtrack linux


#3 john_6767

john_6767
  • Members
  • PipPipPip
  • Advanced Member
  • 99 posts

Posted 08 October 2006 - 04:24 AM

ok cheers,

heres the add page, the displaying of checkboxes in the form doesn't work,

<?php require_once('Connections/cnnTest.php'); ?>
<?php
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "balls_add_form")) {
  $insertSQL = sprintf("INSERT INTO balls (ball_name, ball_desc) VALUES (%s, %s)",
                       GetSQLValueString($_POST['txt_ball_name'], "text"),
                       GetSQLValueString($_POST['txt_ball_desc'], "text"));

  mysql_select_db($database_cnnTest, $cnnTest);
  $Result1 = mysql_query($insertSQL, $cnnTest) or die(mysql_error());
//standard dreamweaver insert code above
//my insert for sizes below
foreach ($_POST["size"] as $sizeID) { 
  $ary = "INSERT INTO balls_sizes (ball_id, size_id) VALUES (" . $ball_id . ", '" . $sizeID . "')"; 
// execute query 
	mysql_select_db($database_cnnTest, $cnnTest);
  $Result2 = mysql_query($ary, $cnnTest) or die(mysql_error());
} 

//end of my insert for sizes


  $insertGoTo = "index.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}

mysql_select_db($database_cnnTest, $cnnTest);
$query_rsSizes = "SELECT * FROM sizes ORDER BY size_name ASC";
$rsSizes = mysql_query($query_rsSizes, $cnnTest) or die(mysql_error());
$row_rsSizes = mysql_fetch_assoc($rsSizes);
$totalRows_rsSizes = mysql_num_rows($rsSizes);
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Balls add page</title>
</head>

<body>
<p>Balls add page</p>
<form id="balls_add_form" name="balls_add_form" method="POST" action="<?php echo $editFormAction; ?>">
  <table width="80%" border="0" cellpadding="0" cellspacing="0">
    <tr>
      <td>Ball Name </td>
      <td><input name="txt_ball_name" type="text" id="txt_ball_name" /></td>
    </tr>
    <tr>
      <td>Ball Desc </td>
      <td><input name="txt_ball_desc" type="text" id="txt_ball_desc" /></td>
    </tr>
    <tr>
      <td>Sizes</td>
      <td>
	  <?php 
	  // Assume that the database returns the list of sizes 
		for ($i=0; $i < mysql_num_rows($rsSizes); $i++) { 
		  $row = mysql_fetch_row($rsSizes); 
		  echo "<input type=\"checkbox\" name=\"size[]\" value=\"" . $row[0] . "\">\n"; 
		} 

	  ?>
	  <input type="checkbox" name="checkbox" value="checkbox" /></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><input type="submit" name="Submit" value="Add Ball" /></td>
    </tr>
  </table>
  <input type="hidden" name="MM_insert" value="balls_add_form">
</form>
</body>
</html>
<?php
mysql_free_result($rsSizes);
?>


#4 .josh

.josh
  • Staff Alumni
  • .josh
  • 14,871 posts

Posted 08 October 2006 - 08:45 AM

when you say "displaying of checkboxes in the form doesn't work" do you mean that you are not getting anything at all displayed, including the actual checkboxes, or do you mean to say that the checkboxes are being displayed, but not the info that should go next to them?

if you mean the 2nd, it's because you aren't actually echoing the data next to your checkbox. it should look something like this:

	  <?php 
	  // Assume that the database returns the list of sizes 
		for ($i=0; $i < mysql_num_rows($rsSizes); $i++) { 
		  $row = mysql_fetch_row($rsSizes);  
		  echo "<input type=\"checkbox\" name=\"size[]\" value=\"" . $row[0] . "\"> {$row[0]}\n"; 
		} 

	  ?>

also just so you know, that code block can be reduced a bit, by doing this instead:

	  <?php 
	  // Assume that the database returns the list of sizes 
		while ($row = mysql_fetch_row($rsSizes)) { 
		    echo "<input type='checkbox' name='size[]' value='{$row[0]}'> {$row[0]}\n"; 
		} 
	  ?>


Did I help you? Feeling generous? Buy me lunch! 
Please, take the time and do some research and find out how much it would have cost you to get your help from a decent paid-for source. A "roll-of-the-dice" freelancer will charge you $5-$15/hr. A decent entry level freelancer will charge you around $15-30/hr. A professional will charge you anywhere from $50-$100/hr. An agency will charge anywhere from $100-$250/hr. Think about all this when soliciting for help here. Think about how much money you are making from the work you are asking for help on. No, we do not expect you to pay for the help given here, but donating a few bucks is a fraction of the cost of what you would have paid, shows your appreciation, helps motivate people to keep offering help without the pricetag, and helps make this a higher quality free-help community :)

#5 john_6767

john_6767
  • Members
  • PipPipPip
  • Advanced Member
  • 99 posts

Posted 08 October 2006 - 09:53 AM

thanks for your help, that second snippet in your post of php returns 4 checkboxes, but the first snippet returns 5..

4 is the correct number as i should have one checkbox for every size and there are 4 sizes in the database table sizes,

how do i write the size_name row from the database next to the checkbox not the number,

cheers

#6 .josh

.josh
  • Staff Alumni
  • .josh
  • 14,871 posts

Posted 08 October 2006 - 05:16 PM

you have to change the 0 in $row[0] to whichever element number holds your size_name.  That is why i use mysql_fetch_array instead of mysql_fetch_row, because instead of guessing, i can just use the name of the row.

  <?php 
	  // Assume that the database returns the list of sizes 
		while ($row = mysql_fetch_array($rsSizes)) { 
		    echo "<input type='checkbox' name='size[]' value='{$row[0]}'> {$row['size_name']}\n"; 
		} 
	  ?>

assuming that size_name is your column name. With mysql_fetch_array by default you still get the number indexed array from fetch_row, as well as the new associative array where you can use the column name, so you can technically use $row[0] in your value='{$row[0]}' but you can change that to value='{$row['column_name_here']}' 

Did I help you? Feeling generous? Buy me lunch! 
Please, take the time and do some research and find out how much it would have cost you to get your help from a decent paid-for source. A "roll-of-the-dice" freelancer will charge you $5-$15/hr. A decent entry level freelancer will charge you around $15-30/hr. A professional will charge you anywhere from $50-$100/hr. An agency will charge anywhere from $100-$250/hr. Think about all this when soliciting for help here. Think about how much money you are making from the work you are asking for help on. No, we do not expect you to pay for the help given here, but donating a few bucks is a fraction of the cost of what you would have paid, shows your appreciation, helps motivate people to keep offering help without the pricetag, and helps make this a higher quality free-help community :)

#7 john_6767

john_6767
  • Members
  • PipPipPip
  • Advanced Member
  • 99 posts

Posted 08 October 2006 - 11:29 PM

ok, that works and displays the field names next to the checkboxes but it doesn't display the last checkbox.. ie if there 5 in database it displays the first 4/

also my updaqte script doesn't work, should be pretty simple stuff?

where have i gone wrong? ???


$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "balls_add_form")) {
  $insertSQL = sprintf("INSERT INTO balls (ball_name, ball_desc) VALUES (%s, %s)",
                       GetSQLValueString($_POST['txt_ball_name'], "text"),
                       GetSQLValueString($_POST['txt_ball_desc'], "text"));

  mysql_select_db($database_cnnTest, $cnnTest);
  $Result1 = mysql_query($insertSQL, $cnnTest) or die(mysql_error());
//standard dreamweaver insert code above
//my insert for sizes below
foreach ($_POST["size"] as $sizeID) { 
  $ary = "INSERT INTO balls_sizes (ball_id, size_id) VALUES (" . $ball_id . ", '" . $sizeID . "')"; 
// execute query 
	mysql_select_db($database_cnnTest, $cnnTest);
  $Result2 = mysql_query($ary, $cnnTest) or die(mysql_error());
} 

//end of my insert for sizes


  $insertGoTo = "index.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}



#8 john_6767

john_6767
  • Members
  • PipPipPip
  • Advanced Member
  • 99 posts

Posted 09 October 2006 - 12:09 AM

i can get the checkboxes to display properly this way but am unsure as to how to loop through the values on the insert.. is this bad practise to do it this way?

maybe i can use
expload(",",$POST['size_id'])
???

        <?php do { ?>
          <input type="checkbox" name="size_id[]" value="<?php echo $row_rsSizes['size_id']; ?>" />
          <?php echo $row_rsSizes['size_name']; ?><br />
          <?php } while ($row_rsSizes = mysql_fetch_assoc($rsSizes)); ?>


ok this worked  ;D, incase anyone is curious i just changed the checkbox field to an array as above and for the insert i did,

now thats the easy bit, onto the update..

if (isset($_POST['size_id'])){
		foreach ($_POST['size_id'] as $size_id) {

//insert here
                          }
}





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users