Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

multiple items being inserted as one item

Posted on 2011-09-07
15
Medium Priority
?
308 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 6
  • 2
  • +1
15 Comments
 
LVL 8

Expert Comment

by:pvlier
ID: 36498595
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
ID: 36498609
@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
ID: 36499212
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:peter_coop
ID: 36501356
@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
ID: 36502414
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 111

Expert Comment

by:Ray Paseur
ID: 36502427
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
ID: 36503580
This is the result of the var_dump($_POST);

["BRVbrtrv_boxnumber"]=>
  array(2) {
    [0]=>
    string(3) "ghh"
    [1]=>
    string(3) "fdd"
  }
0
 

Author Comment

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

Expert Comment

by:hielo
ID: 36503637
>>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
ID: 36503646
FYI: Do NOT use the explode() line as previously suggested in ID:36502414
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36503697
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
ID: 36503747
>>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
ID: 36503762
@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 1000 total points
ID: 36504712
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
ID: 36505120
thanks very much
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Containers like Docker and Rocket are getting more popular every day. In my conversations with customers, they consistently ask what containers are and how they can use them in their environment. If you’re as curious as most people, read on. . .
When it comes to security, close monitoring is a must. According to WhiteHat Security annual report, a substantial number of all web applications are vulnerable always. Monitis offers a new product - fully-featured Website security monitoring and pr…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses

610 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