Solved

multiple items being inserted as one item

Posted on 2011-09-07
15
298 Views
Last Modified: 2012-05-12
I am trying to accept multiple items from a form and when they reach php for processing, split the items and treat them as seperate items to insert into db. What is happening at the moment, is that the items are being inserted into the db as one item. For example, i enter item1,item2,item3. This is being inserted into the db in one column. all three items in one column. How can I correct my code to achieve this. Many thanks
foreach($_POST['BRV-brtrv-boxnumber'] as $i=>$value){
$_POST['BRV-brtrv-boxnumber'][$i]=mysql_real_escape_string($value);
}
$boxnumber = implode( ',', $_POST['BRV-brtrv-boxnumber']);

$query = 'INSERT INTO `act` (`service`, `activity`, `department`, `company`,  `address`, `user`, `item`, `destroydate`, `date`, `new`)
         VALUES (\''.$service.'\', \''.$activity.'\', \''.$department.'\', \''.$company.'\', \''.$address.'\', \''.$authorised.'\', \''.strtoupper($boxnumber).'\', NULL, NOW(), \''.$new.'\');';
mysql_query($query) or die('Error, query failed');

Open in new window

0
Comment
Question by:peter_coop
  • 6
  • 6
  • 2
  • +1
15 Comments
 
LVL 8

Expert Comment

by:pvlier
Comment Utility
I expect you are gettting values from multiple checkboxes, or a multiselect?

You should then use "<name>[]"as the name. For example:

<input type="checkbox" name="test[]" value="123"> 123
<input type="checkbox" name="test[]" value="abc"> abc
<input type="checkbox" name="test[]" value="456"> 456

<select name="test[]" multiple="multiple">
      <option value="one">one</option>
      <option value="two">two</option>
      <option value="three">three</option>
      <option value="four">four</option>
      <option value="five">five</option>
</select>

then you can get the value with:

 
$test = array();

if (isset($_POST["test"]))
    {
    $test=$_POST['test'];
    if ($test)
        {
         foreach ($test as $t)
            {
            $query = 'INSERT INTO `act` (`service`, `activity`, `department`, `company`, `address`, `user`, `item`, `destroydate`, `date`, `new`) VALUES (\''.$service.'\', \''.$activity.'\', \''.$department.'\', \''.$company.'\', \''.$address.'\', \''.$authorised.'\', \''.strtoupper($t).'\', NULL, NOW(), \''.$new.'\');';
            mysql_query($query) or die('Error, query failed');
            }
        }
    }

Open in new window

0
 

Author Comment

by:peter_coop
Comment Utility
@pvlier
I am using jquery to input form values.
for(var i = 0;i < $(this).val();i++) {
$("#BRVbrtrv_boxnumber").append('<div data-role="fieldcontain"><label for="BRVbrtrv_boxnumber" class="ui-input-text">Enter box ' + (i + 1) + ' number:</label><input type="text" name="BRVbrtrv_boxnumber['+i+']" id="BRVbrtrv_boxnumber['+i+']" class="BRV_boxnumber ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-c" /></div>')
}

Open in new window

0
 
LVL 82

Expert Comment

by:hielo
Comment Utility
try:
foreach($_POST['BRV-brtrv-boxnumber'] as $i=>$value){
	$_POST['BRV-brtrv-boxnumber'][$i]=mysql_real_escape_string($value);
	$query = 'INSERT INTO `act` (`service`, `activity`, `department`, `company`,  `address`, `user`, `item`, `destroydate`, `date`, `new`)
         VALUES (\''.$service.'\', \''.$activity.'\', \''.$department.'\', \''.$company.'\', \''.$address.'\', \''.$authorised.'\', \''.strtoupper($_POST['BRV-brtrv-boxnumber'][$i]).'\', NULL, NOW(), \''.$new.'\');';
	mysql_query($query) or die('Error, query failed');
}

Open in new window

0
 

Author Comment

by:peter_coop
Comment Utility
@hielo
now it is inputing just 1 value, the last entry. Here is what json is returning. thanks

boxcount: "2"
boxnumber: "rff,tgg"
0
 
LVL 82

Expert Comment

by:hielo
Comment Utility
If I understand you correctly, $_POST['BRV-brtrv-boxnumber'] is a comma-delimited "string"? If so, try:
$_POST['BRV-brtrv-boxnumber']=explode(',',$_POST['BRV-brtrv-boxnumber']);
foreach($_POST['BRV-brtrv-boxnumber'] as $i=>$value){
	$_POST['BRV-brtrv-boxnumber'][$i]=mysql_real_escape_string($value);
	$query = 'INSERT INTO `act` (`service`, `activity`, `department`, `company`,  `address`, `user`, `item`, `destroydate`, `date`, `new`)
         VALUES (\''.$service.'\', \''.$activity.'\', \''.$department.'\', \''.$company.'\', \''.$address.'\', \''.$authorised.'\', \''.strtoupper($_POST['BRV-brtrv-boxnumber'][$i]).'\', NULL, NOW(), \''.$new.'\');';
	mysql_query($query) or die('Error, query failed');
}

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Use var_dump($_POST) to print out the contents of the request.  It should be fairly easy to write the code once you can see the data.
0
 

Author Comment

by:peter_coop
Comment Utility
This is the result of the var_dump($_POST);

["BRVbrtrv_boxnumber"]=>
  array(2) {
    [0]=>
    string(3) "ghh"
    [1]=>
    string(3) "fdd"
  }
0
Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

 

Author Comment

by:peter_coop
Comment Utility
@hielo
the result of your code change:
"boxnumber": "Array", thanks
0
 
LVL 82

Expert Comment

by:hielo
Comment Utility
>>This is the result of the var_dump($_POST);
IF that is true, then this should work:
foreach($_POST['BRVbrtrv_boxnumber'] as $i=>$value){
	$_POST['BRVbrtrv_boxnumber'][$i]=mysql_real_escape_string($value);
	$query = 'INSERT INTO `act` (`service`, `activity`, `department`, `company`,  `address`, `user`, `item`, `destroydate`, `date`, `new`)
         VALUES (\''.$service.'\', \''.$activity.'\', \''.$department.'\', \''.$company.'\', \''.$address.'\', \''.$authorised.'\', \''.strtoupper($_POST['BRVbrtrv_boxnumber'][$i]).'\', NULL, NOW(), \''.$new.'\');';
echo 'attempting to execute', htmlentities($query,ENT_QUOTES);
	mysql_query($query) or die('Error, query failed');
}

//It should echo one INSERT query for every item in BRVbrtrv_boxnumber

NOTE: ON your original post you are referencing:
['BRV-brtrv-boxnumber']

but the var_dump() shows:
["BRVbrtrv_boxnumber"]

(notice that the first hyphen is not there and the second hyphen is now an underscore). The key HAS to match what you ACTUALLY have in $_POST.

Open in new window

0
 
LVL 82

Expert Comment

by:hielo
Comment Utility
FYI: Do NOT use the explode() line as previously suggested in ID:36502414
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
The key HAS to match what you ACTUALLY have in $_POST. Wait!  Why wasn't I informed?!  

;-)

And it is case-sensitive, and it will drive you nuts if you put special characters in it because PHP will mung the key in some cases.  A safe practice is to use only letters, numbers and the underscore.  The relationship of the form input to the PHP action script is illustrated by this little script.
<?php // RAY_post_example.php
error_reporting(E_ALL);
echo "<pre>"; // MAKE IT EASY TO READ



// THIS ILLUSTRATES THE RELATIONSHIP BETWEEN THE 'ACTION' AND THE 'FORM' WHEN COMBINED INTO A SINGLE PHP SCRIPT FILE



// SET A DEFAULT VALUES FOR A VARIABLE TO PREPOPULATE THE FORM - THIS COULD COME FROM A DATA BASE, OR MIGHT BE EMPTY
$my_INPUT_Field = 'ORIGINAL DATA';



// HAS ANYTHING BEEN POSTED? IF SO, $_POST IS SET AND CONTAINS THE DATA
if (!empty($_POST))
{
    // SHOW THE POST ARRAY
    var_dump($_POST);

    // IF THE FORM WAS FILLED IN, COPY THE INPUT INTO OUR VARIABLE
    if (!empty($_POST["my_INPUT_Field"]))
    {
        $my_INPUT_Field = $_POST["my_INPUT_Field"];
    }

    // THIS IS THE END OF THE ACTION SCRIPT
    echo 'ACTION COMPLETED';
}



// THIS IS THE FORM SCRIPT CREATED IN HEREDOC NOTATION
$form = <<<ENDFORM
<form method="post">
TYPE SOMETHING HERE:
<input type="text"   name="my_INPUT_Field"   value="$my_INPUT_Field" />
<input type="hidden" name="my_HIDDEN_Field"  value="Not Really Much of a Secret" />
<input type="submit" name="my_SUBMIT_Button" value="go" />
</form>
ENDFORM;

// WRITE THE FORM TO THE BROWSER
echo $form;

Open in new window

0
 
LVL 82

Expert Comment

by:hielo
Comment Utility
>>Wait!  Why wasn't I informed?!
If you have to ask then http://www.sitepoint.com/books/phpmysql4/ must not be as good as you keep advertising everyday!

LOL - you set yourself up for that one!!!
0
 

Author Comment

by:peter_coop
Comment Utility
@hielo
still only outputting the second value instead of 2. I have included the whole code and taken the db out of the equation until I can get json to return correct values. I can confirm that BRVbrtrv_boxnumber is the correct name.  Thanks
<?php include("JSON.php"); ?>
<?php
session_start();

$new = 1;
$activity = 'Box Retrieval';
$company = $_SESSION['idcode'];
$authorised = mysql_real_escape_string($_POST['BRV_brtrvrb']);
$service = mysql_real_escape_string($_POST['BRV-id-service-type']);
$department = mysql_real_escape_string($_POST['BRV-brtrv-department']);
$address = mysql_real_escape_string($_POST['BRV-brtrv-address']);
$boxcount = mysql_real_escape_string($_POST['BRV-brtrv-slider']);
//var_dump($_POST);
foreach($_POST['BRVbrtrv_boxnumber'] as $i=>$value){
	$boxnumber = $_POST['BRVbrtrv_boxnumber'][$i]=mysql_real_escape_string($value);

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
header("Content-type: application/json");
$json = "";
if(empty($service)) {
$json .= "{\"ErrorService\": \"ERROR: You mest select a service level\"}";
 }

else
if($department=="Choose Department") {
$json .= "{\"ErrorService\": \"ERROR: You must select a department\"}";
 }

else
if($address=="Choose Address") {
$json .= "{\"ErrorService\": \"ERROR: You must select a retrieval address\"}";
 }

else
if(empty($boxnumber)) {
$json .= "{\"ErrorService\": \"ERROR: You must enter a box for retrieval\"}";
 }

else
{
$json .= "{\n";
$json .= "\"boxnumber\": \"".$boxnumber."\",\n";
$json .= "\"boxcount\": \"".$boxcount."\"\n";
$json .= "}\n";
}
}
echo $json;

Open in new window

0
 
LVL 82

Accepted Solution

by:
hielo earned 250 total points
Comment Utility
On your original post you are trying to INSERT into a db, which is SIGNIFICANTLY different from what you are trying to do on your last post, which is to generate json output. Try:
<?php include("JSON.php"); ?>
<?php
session_start();

$new = 1;
$activity = 'Box Retrieval';
$company = $_SESSION['idcode'];
$authorised = mysql_real_escape_string($_POST['BRV_brtrvrb']);
$service = mysql_real_escape_string($_POST['BRV-id-service-type']);
$department = mysql_real_escape_string($_POST['BRV-brtrv-department']);
$address = mysql_real_escape_string($_POST['BRV-brtrv-address']);
$boxcount = mysql_real_escape_string($_POST['BRV-brtrv-slider']);
$boxnumber=array();
foreach($_POST['BRVbrtrv_boxnumber'] as $i=>$value){
	$boxnumber[]= sprintf( '"%s"',mysql_real_escape_string($value) );
}
$boxnumber=implode(',',$boxnumber);
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
header("Content-type: application/json");
$json = "";
if(empty($service)) {
$json .= "{\"ErrorService\": \"ERROR: You mest select a service level\"}";
 }

else
if($department=="Choose Department") {
$json .= "{\"ErrorService\": \"ERROR: You must select a department\"}";
 }

else
if($address=="Choose Address") {
$json .= "{\"ErrorService\": \"ERROR: You must select a retrieval address\"}";
 }

else
if(empty($boxnumber)) {
$json .= "{\"ErrorService\": \"ERROR: You must enter a box for retrieval\"}";
 }

else
{
$json .= '{'.PHP_EOL;
$json .= '"boxnumber": ['.$boxnumber.'],'.PHP_EOL;
$json .= '"boxcount": "'.$boxcount.'"'.PHP_EOL;
$json .= '}'.PHP_EOL;
}

echo $json;

Open in new window

0
 

Author Closing Comment

by:peter_coop
Comment Utility
thanks very much
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

This article discusses four methods for overlaying images in a container on a web page
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Any person in technology especially those working for big companies should at least know about the basics of web accessibility. Believe it or not there are even laws in place that require businesses to provide such means for the disabled and aging p…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now