Link to home
Start Free TrialLog in
Avatar of peter_coop
peter_coopFlag for United Kingdom of Great Britain and Northern Ireland

asked on

multiple items being inserted as one item

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

Avatar of pvlier
pvlier
Flag of Netherlands image

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

Avatar of peter_coop

ASKER

@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

Avatar of hielo
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

@hielo
now it is inputing just 1 value, the last entry. Here is what json is returning. thanks

boxcount: "2"
boxnumber: "rff,tgg"
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

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.
This is the result of the var_dump($_POST);

["BRVbrtrv_boxnumber"]=>
  array(2) {
    [0]=>
    string(3) "ghh"
    [1]=>
    string(3) "fdd"
  }
@hielo
the result of your code change:
"boxnumber": "Array", thanks
>>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

FYI: Do NOT use the explode() line as previously suggested in ID:36502414
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

>>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!!!
@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

ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks very much