Insert selected dynamic checkboxes as array

I need a bit of help posting the results of dynamic check boxes as an array to the database. I have figured out how to get the checkboxes to load into the form but do not understand how to post the results of the chosen checkboxes as an array and insert the array into the db. Right now it only inserts the first chosen checkbox by itself.

Here is what I have so far:

        <?php require_once("Connection.php");

$sql = "SELECT * FROM agents"; 
$pResult=mysql_query($sql) or die(mysql_error()); 

if(mysql_num_rows($pResult) == 0) 
    print "There are No Records";     
    while($tmp = mysql_fetch_assoc($pResult)) 
        echo "<input type=\\"checkbox\\" name=\\"agent_id\\" value=\\"".$tmp["ID"]."\\" />"; echo $tmp['name'];
		echo "<br />"; 

To close off this post I wanted to say thanks for all your input. I was able to get it working by changing the database column from an integer to a varchar and then sending the data as text instead of a number.

Can’t wait to stop referring to myself as a noob!

I want it to pass those agent IDs into the customer table as an array.

Yep, I wanted to show you how you turn the array of agents from this;

$_POST['agent_id'][] = 1;
$_POST['agent_id'][] = 7;

var_dump( $_POST['agent_id'] );

//  0 => int 1
//  1 => int 7

into this;

$t = implode( "," , $_POST['agent_id'] );
echo $t ;

in order to answer your immediate question.

Then I went on and tried to point out that while it will work it may place constraints in the future if you have not questioned the users of your system about what kind of management intelligence they expect to be able to query for, thats all :wink: which is not strictly a PHP solution, but deals with the importance of how you model your data in the database.

All things in time eh? Remember [google]database normalization[/google], you can discount it if you wish - but its best to be aware of it - even early on.


$WA_fieldValuesStr = ""

If I understand your question, it is how to insert an array of id numbers into a single field.

Someone has explained how to return an array from your HTML form, now you need to
a) check that even one exists
b) turn that array into a string, and lets say that is a csv string.

$agent_string = implode( ',' , $_POST['agent_id'] ) ;

then insert $agent_string into your database. I think that is answering the question you asked.

However, doing that is going possibly cause you problems further down the line, and really most common wisdom suggests that you ought to be looking to create a table which contains these relationships - all part of database normalization, which you can look up.

Here is a really simple example of what I mean, imagining your “agents” are sales agents dealing with “companies” :

table: contacts (contact_id, contact_name)
1 - "big company"
2 - "small company"

table: agents (agent_id, agent_name )
1 - "Bob"
2 - "Ted" 

//referential table
table contact_agent (contact_ref, agent_ref)
1 - 1
1 - 2
2 - 1

With a suitable sql statement you can use joins to discover that in the above contrived example Bob is the agent for both companies, while Ted is the contact for just “small company”

This allows you to easily ask the questions:

Which companies is Bob the agent for?
Which companies is Bob not the agent for?
Which companies have no agent?
Which companies have got 2 agents?
Which agent has the biggest/smallest workload?
What is the average client number our agents currently have?
Who are the agents for “big company”?

These types of queries, when joined to other tables can reveal a lot of management account information - one can imagine that joined with sales data you could find out which companies spend the most but have the least agents, and so on - none of which will be very easy or even doable without multiple complex selects do unpick the imploded array you seem to be asking to store in your database.

Using a system as outlined might be more appropriate for you, but you know your own data better than us.

Okay so I understand the creates the array for the name but I really don’t get the rest of what is happening or how to apply it.

Maybe if I show you the insert code on the page you could tell me how to configure it?

if (isset($_POST["Insert_x"])) // Trigger
  $WA_connection = $Polk;
  $WA_table = "test_table";
  $WA_sessionName = "WADA_Insert_test_table";
  $WA_redirectURL = "test_table_Detail.php";
  $WA_keepQueryString = false;
  $WA_indexField = "ID";
  $WA_fieldNamesStr = "agent_id";
  $WA_fieldValuesStr = "".((isset($_POST["agent_id"]))?$_POST["agent_id"]:"")  ."";
  $WA_columnTypesStr = "none,none,NULL";
  $WA_fieldNames = explode("|", $WA_fieldNamesStr);
  $WA_fieldValues = explode("|", $WA_fieldValuesStr);
  $WA_columns = explode("|", $WA_columnTypesStr);
  $WA_connectionDB = $database_Polk;
  mysql_select_db($WA_connectionDB, $WA_connection);
  if (!session_id()) session_start();
  $insertParamsObj = WA_AB_generateInsertParams($WA_fieldNames, $WA_columns, $WA_fieldValues, -1);
  $WA_Sql = "INSERT INTO `" . $WA_table . "` (" . $insertParamsObj-&gt;WA_tableValues . ") VALUES (" . $insertParamsObj-&gt;WA_dbValues . ")";
  $MM_editCmd = mysql_query($WA_Sql, $WA_connection) or die(mysql_error());
  $_SESSION[$WA_sessionName] = mysql_insert_id();
  if ($WA_redirectURL != "")  {
    if ($WA_keepQueryString && $WA_redirectURL != "" && isset($_SERVER["QUERY_STRING"]) && $_SERVER["QUERY_STRING"] !== "" && sizeof($_POST) &gt; 0) {
      $WA_redirectURL .= ((strpos($WA_redirectURL, '?') === false)?"?":"&").$_SERVER["QUERY_STRING"];
    header("Location: ".$WA_redirectURL);

This seems so easy but I just cant get it. My knowledge of PHP is very little but enough that I am in trouble now. I appreciate your advice.

What RNEL have suggested is absolutely correct.
Also dont forget to check if the checkboxes are checked or not. If you are using some validation then its good otherwise foreach will generate an ugly warning if no checkboxes are checked

you can validate foreach this way

foreach($_POST['agent_id'] AS $agent_id){
//insert here

here’s the basic logic

should be


and when you insert

foreach($_POST['agent_id'] AS $agent_id){
//insert here

filter user input and escape before inserting :slight_smile:

That is precisely what I am doing. I have already created the agent table and have it functioning. This insert page is for the company form which has checkboxes that dynamically pulls the list of all agents in the agent table and allows the user to select which of those agents are the agents for the company. After the user selects, say agent 1 and agent 5, I want it to pass those agent IDs into the customer table as an array.

This is the same as it sounds like you are suggesting right?