Part of the EllisLab Network
   
 
Can’t insert checkbox array into database
Posted: 19 January 2007 11:52 AM   [ Ignore ]  
Summer Student
Total Posts:  9
Joined  01-19-2007

I cannot get CodeIgnitor to insert into MySQL checkbox values that originate from an array. I’ve seen other similar threads, although somewhat different in many cases. I don’t even care about validation. I just want the insert to be completed.

What I’ve got is a routine PHP checkbox array in a form:

<input name="Request_Value[]" type="checkbox" value="Quote" />
<
input name="Request_Value[]" type="checkbox" value="Demo" />
<
input name="Request_Value[]" type="checkbox" value="Call-back" />


In the controller, I tried adding my old PHP “for each loop” to append the array values into a string, ending ultimately with $Request which is the name of the field in the database:

foreach($_POST['Request_Value']  as  $values_string)  
        
{
        $Request
.= "$values_string, ";
        
}
        $this
->db->insert('leads', $_POST);

This isn’t working. I get two errors:

A PHP Error was encountered
Severity
: Notice
Message
: Array to string conversion
Filename
: mysql/mysql_driver.php
Line Number
: 406

AND ...

An Error Was Encountered
Error Number
: 1054
Unknown column
'Array' in 'field list'
INSERT INTO leads (First_Name, Last_Name, Company, Phone, Email, Opt_in, Software, Lead_Received, Lead_Source, Promotion_Code, Request, Situation, Comments) VALUES ('T', 'S', 'sq', '(412) 111-1111', 't@s.net', 'No', 'QuickBooks Premier', 'Outbound', 'Prospecting Call from Sales', 'OPCFS100 Call Prospecting Call From Sales', Array, 'Just Researching', 'CodeIgnitor Test')

It just tries to insert—> Array ... Anyone have any ideas?

Profile
 
 
Posted: 19 January 2007 01:51 PM   [ Ignore ]   [ # 1 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  310
Joined  08-16-2006

It appears you’re attempting to insert the array itself instead of the values (as a comma-delimited string.)

I would suggest replacing the foreach with something like this (untested)

if (isset($_POST['Request_Value']) && is_array($_POST['Request_Value']))
{
  $_POST[
'Request_Value'] = implode(", ", $_POST['Request_Value']);
}
else
{
  $_POST[
'Request_Value'] = '';
}

Update: added the else condition in case none of the checkboxes are ticked.

Profile
 
 
Posted: 19 January 2007 07:35 PM   [ Ignore ]   [ # 2 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  481
Joined  03-08-2006

PHP functions serialize() and unserialize() may be of some use to you on this.

 Signature 

Flickr | Last.fm | Del.icio.us

Profile
 
 
Posted: 19 January 2007 08:52 PM   [ Ignore ]   [ # 3 ]  
Summer Student
Total Posts:  9
Joined  01-19-2007

This worked, thanks.

if (isset($_POST['Request_Value']) && is_array($_POST['Request_Value']))
{
  $_POST[
'Request_Value'] = implode(", ", $_POST['Request_Value']);
}

But I also changed the name of the field in my database from “Request” to “Lead Request.”

Profile
 
 
Posted: 02 February 2007 09:34 PM   [ Ignore ]   [ # 4 ]  
Lab Assistant
RankRank
Total Posts:  128
Joined  07-20-2006

Thanks guys, that worked really well for me too smile

Profile
 
 
Posted: 05 February 2007 11:21 AM   [ Ignore ]   [ # 5 ]  
Summer Student
Avatar
Total Posts:  3
Joined  02-05-2007

Greetings from the 3rd World.

I’m by no means an experienced php writer or even the worse writer, as sad as it seems i’m nothing but a poser, but willing to learn.

on the past days i’ve benn struggling with something like’s described on this thread but seems that my lack of knowleadge is so great that i can’t get to understand the examples. (i’ve been searching all over the net for this answer for almost two months now.)


The Issue:
I have an Indert Record page to submit data to a MySQL database and a couple of fields have the option for the user to insert more than one value into it and i’m baking my brains off to figure out how, cos (as u all might already know very well) a regular select box or group of checkboxes only post the last value in the array selected. So i heard from a dude that the answer is an array, but the best i cud get is to post into the table the word “ARRAY” instead of my values.

This is what i’m doing (the actual table contains 32 fields to fill up, so i will post just a few, i’ll fill the blanks later)


For the HEAD tag of the PHP page:

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form")) {
  $insertSQL
= sprintf("INSERT INTO Clientes (client_id, Nombre, Keywords, playera, aplicaciones, aplicOp, otros, logoLink) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
  
                       
GetSQLValueString($_POST['client_id'], "int"),
                       
GetSQLValueString($_POST['Nombre'], "text"),
                       
GetSQLValueString($_POST['Keywords'], "text"),
                       
GetSQLValueString($_POST['playera[]'], "text"),
                       
GetSQLValueString(isset($_POST['aplicaciones']) ? "true" : "", "defined","'Y'","'N'"),
                       
GetSQLValueString(isset($_POST['aplicOp']) ? "true" : "", "defined","'Y'","'N'"),
                       
GetSQLValueString(isset($_POST['otros']) ? "true" : "", "defined","'Y'","'N'"),
                       
GetSQLValueString($_POST['logoLink'], "text"));

  
mysql_select_db($database_playerasConn, $playerasConn);
  
$Result1 = mysql_query($insertSQL, $playerasConn) or die(mysql_error());

  
$insertGoTo = "agregado.php";
  if (isset(
$_SERVER['QUERY_STRING'])) {
    $insertGoTo
.= (strpos($insertGoTo, '?')) ? "&" : "?";
    
$insertGoTo .= $_SERVER['QUERY_STRING'];
  
}

and for the BODY:

<form method="post" name="form" action="<?php echo $editFormAction; ?>">
      <
table align="center">
          <
tr valign="baseline">
            <
td align="right" valign="top" nowrap class="smallTitleBold">Nombre:</td>
            <
td valign="top" class="normal"><input name="Nombre" type="text" class="normal" value="" size="30" maxlength="60"></td>
          </
tr>
          <
tr valign="baseline">
            <
td align="right" valign="top" nowrap class="smallTitleBold">Keywords:</td>
            <
td valign="top" class="normal"><textarea name="Keywords" cols="40" rows="5" class="normal"></textarea>            </td>
          </
tr>
          <
tr valign="baseline">
            <
td align="right" valign="top" nowrap class="smallTitleBold">Playera:</td>
            <
td valign="top" class="normal">&nbsp;
              <
select name="playera[]" size="5" multiple="multiple" class="normal" id="playera[]">
                
<?php
do {  
?>
                
<option value="<?php echo $row_rsPlayeras['valor']?>"><?php echo $row_rsPlayeras['nombre']?></option>
                
<?php
}
while ($row_rsPlayeras = mysql_fetch_assoc($rsPlayeras));
  
$rows = mysql_num_rows($rsPlayeras);
  if(
$rows > 0) {
      mysql_data_seek
($rsPlayeras, 0);
      
$row_rsPlayeras = mysql_fetch_assoc($rsPlayeras);
  
}
?>
              
</select></td>
          </
tr>
          <
tr valign="baseline">
            <
td align="right" valign="top" nowrap class="smallTitleBold">Aplicaciones:</td>
            <
td valign="top" class="normal"><input name="aplicaciones" type="checkbox" id="aplicaciones" value="checkbox" /></td>
          </
tr>
          <
tr valign="baseline">
            <
td align="right" valign="top" nowrap class="smallTitleBold">AplicOp:</td>
            <
td valign="top" class="normal"><input type="checkbox" name="aplicOp" value="" ></td>
          </
tr>
          <
tr valign="baseline">
            <
td align="right" valign="top" nowrap class="smallTitleBold">Otros:</td>
            <
td valign="top" class="normal"><input type="checkbox" name="otros" value="" ></td>
          </
tr>
          <
tr valign="baseline">
            <
td align="right" valign="top" nowrap class="smallTitleBold"><input type="hidden" name="MM_insert" value="form" />
              <
input type="hidden" name="client_id" value="" /></td>
            <
td valign="top" class="normal"><input name="add" type="submit" class="normal" id="add" value="Agregar Registro">
            <
input name="clear" type="reset" class="normal" id="clear" value="Borrar Forma" /></td>
          </
tr>
        </
table>
        </
form>

Explanation: The selectbox named “playeras” is filled dynamically from another table from the DB (cos is very possible that the options might change on the future) and for this example that’s exactly the one i need to array so the multiple values get posted on the DB table and not just the last selected or the “ARRAY” word.

Any help for a newby?
Please?
i pay on mexican soda.

 Signature 

GREETINGS FROM THE 3RD WORLD!

Profile
 
 
Posted: 05 February 2007 01:38 PM   [ Ignore ]   [ # 6 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  310
Joined  08-16-2006

Please don’t misinterpret this as sounding unfriendly, but this forum is reserved for the discussion of PHP as it relates to the Code Igniter framework. You might have more success with general PHP questions in a news group such as comp.lang.php.

That said, your example is somewhat convoluted so my advice is to start simple. For learning and testing purposes, scale back your form to a couple of checkboxes. Once you’re able to successfully insert the array values, you can gradually add the other elements back in—performing regression testing along the way.

Profile
 
 
Posted: 05 February 2007 08:16 PM   [ Ignore ]   [ # 7 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  486
Joined  09-14-2006
El Brujo - 05 February 2007 11:21 AM

i pay on mexican soda.

Do you mean the kind that comes in a bag? haha

You’ll need to either join the values into a string or store each one separately as it’s own record in a separate table. The first one is the simplest, but not the best in terms of db design.

$_POST['playeras'] = implode('|', $_POST['playeras']);

insert as usual ...

Which ever you choose, you’ll need to rebuild your array when selecting from the db again.

$row = $this->db->get('table')->row();
$row->playeras = explode('|', $row->playeras);

continue
with code ...

 Signature 

Code Igniter 1.5.4 / CentOS 5 / PHP 5.2.3 / Apache 2.2.2 / MySQL 5.0.27

Profile
 
 
Posted: 06 February 2007 04:13 PM   [ Ignore ]   [ # 8 ]  
Summer Student
Total Posts:  4
Joined  02-06-2007

Another way (in my view the most elegant) would be to work with bytes - that way you can even search for any combination of checkboxes in the database.

this is how i encode data for storage in the database:

for($i=0;$i<30;$i+=3)
{
  $options += $_POST[‘option’][$i] << $i;
}

mysql then allows you to search for records where individual bits are set.

And back to normal values:

  for($i=0; $i<30; $i+=3)
  {
      $option$i]=0;
     
      if($row[‘option’]>>$i &1)
      {
        $option[$i]=1;
      }
}
}

andreas

Profile
 
 
Posted: 07 February 2007 01:31 AM   [ Ignore ]   [ # 9 ]  
Summer Student
Avatar
Total Posts:  3
Joined  02-05-2007
Bacteria Man - 05 February 2007 01:38 PM

Please don’t misinterpret this as sounding unfriendly, but this forum is reserved for the discussion of PHP as it relates to the Code Igniter framework. You might have more success with general PHP questions in a news group such as comp.lang.php.

That said, your example is somewhat convoluted so my advice is to start simple. For learning and testing purposes, scale back your form to a couple of checkboxes. Once you’re able to successfully insert the array values, you can gradually add the other elements back in—performing regression testing along the way.

Pues que fresa, no?

 Signature 

GREETINGS FROM THE 3RD WORLD!

Profile
 
 
Posted: 07 February 2007 01:35 AM   [ Ignore ]   [ # 10 ]  
Summer Student
Avatar
Total Posts:  3
Joined  02-05-2007
joeles - 05 February 2007 08:16 PM
El Brujo - 05 February 2007 11:21 AM

i pay on mexican soda.

Do you mean the kind that comes in a bag? haha

 

No, i meant the kind that is served on paper cups, lol

joeles - 05 February 2007 08:16 PM

You’ll need to either join the values into a string or store each one separately as it’s own record in a separate table. The first one is the simplest, but not the best in terms of db design.

$_POST['playeras'] = implode('|', $_POST['playeras']);

insert as usual ...

Which ever you choose, you’ll need to rebuild your array when selecting from the db again.

$row = $this->db->get('table')->row();
$row->playeras = explode('|', $row->playeras);

continue
with code ...

Problem solved, not exactly with this code, but the aproaching of the problem was inspiration enough for a bit od JavaScript that closed the deal. Thanks a bunch to all that participated, even when this ain’t the right place to ask such small problems when other people have larger egos.

Thanks a bunch again.. stay tuned for your paper cups wink

 Signature 

GREETINGS FROM THE 3RD WORLD!

Profile
 
 
   
 
 
Post Marker Legend
New Topic New posts Hot Topic Hot Topic with new posts New Poll New Poll Moved Topic Moved Topic Sticky Topic Sticky topic
Old Topic No new posts Hot Old Topic Hot Topic with no new posts Old Poll Old Poll Closed Topic Closed Topic Announcement Announcements
Theme
Change Theme
Visitor Statistics
The most visitors ever was 719, on June 06, 2008 10:16 AM
Total Registered Members: 66415 Total Logged-in Users: 34
Total Topics: 84757 Total Anonymous Users: 2
Total Replies: 454849 Total Guests: 232
Total Posts: 539606    
Members ( View Memberlist )