Jump to content

Is it possible to achieve what I am attempting?


Bl4ckMaj1k

Recommended Posts

I have a form which has both radio buttons and textfields. Each individual radio button is associated with a form field. For this example, lets say the Radio button references a tool name and the form field represents a quantity, or number of tools needed for a certain job. So the form would look as follows:

 

o Some Tool                Quantity ___ (<-- lets pretend thats a form field)

 

The question is, how would I go about adding the tool and quantity to the same row in the database if I am creating a new row? The simple way would be have each radio button and quantity be its own entity in the HTML. For example:

 

<input name="tool1" type="radio" value="Hammer" />
<input name="tool_quantity1" type="text" />

<input name="tool2" type="radio" value="Wrench" />
<input name="tool_quantity2" type="text" />

 

However easy this method may be, and however functional it may work, it is not how I wish to achieve this because we are talking maybe 100 tools. I think it would be easier using some kind of loop function that goes through an array of anything that has some form of data stored in it. For example, instead of the code being the above, I would like to change it to the following:

 

<input name="tools[]" type="radio" value="Hammer" />
<input name="tools_quantity[]" type="text" />

 

I understand the basic foreach function

 

foreach ($_POST['tools'] as $someVariableName) {
//do some stuff
}

 

But I don't understand how I can get the value of 2 different form fields and have them associated with one another. I want the tool and the quantity of tools to be stored in the same row. How is this done? Is this even possible using a loop function like foreach or while? Please help! As always, any help would be greatly appreciated!!

 

Bl4ck Maj1k

 

Link to comment
Share on other sites

You have some contradictory information in your post. If you have a radio button group to select the item then you only need one quantity field since you could only select one item. But, you don't need a separate selection for the item vs. the quantity input at all. Just create quantity text inputs for each item. Then on the processing page, only process the text fields that have values.

 

Example form:

<input name="quantity[hammerID]" type="text" /> Hammer

<input name="quantity[wrenchID]" type="text" /> Wrench

 

Then on the processing page, do something like this:

$queryValues = array();
foreach($_POST['quantity'] as $itemID => $quantity)
{
    $quantity = (int) $quantity;
    if($quantity > 0)
    {
        $queryValues[] = "($itemID, $quantity)";
    }
}
$query = "INSERT INTO [table_name] (itemID, itemQty) VALUES " . implode(", ", $queryValues);

Link to comment
Share on other sites

Oops!!! Correction to my post. I am not using radio buttons. I am actually using checkboxes!!! I am so sorry...does this change your suggested code?

 

Not really. At first I was going to suggest checkboxes, but when I though about it further I realized the checkboxes were not needed either. You could just process the text fields for the quantity inputs - just show a label next to each one. If you really want to use checkboxes, you can.

 

Sample form

<input name="tools[]" type="radio" value="hammerID" /> Hammer
<input name="quantity[hammerID]" type="text" />

<input name="tools[]" type="radio" value="wrenchID" /> Wrench
<input name="quantity[wrenchID]" type="text" />

 

Sample processing code

$queryValues = array();
foreach($_POST['tools'] as $itemID)
{
    $quantity = (int) $_POST['quantity'][$itemID];
    if($quantity > 0)
    {
        $queryValues[] = "($itemID, $quantity)";
    }
}
$query = "INSERT INTO [table_name] VALUES " . implode(", ", $queryValues);

Link to comment
Share on other sites

Wow this just blew my mind. I think I understand whats going on. I am going to make an attempt at explaining and you just correct me if I am confused anywhere...

 

So first, you establish the radio button, or checkbox...whichever I decide to use. The name has the array [] brackets meaning that whenever thats checked, the value of that will be recorded. The value in this case being hammer ID. Next you work out the input for the texfield. This is where I am kind of confused (please see below questions). I believe you need a reference point so your code knows what quantity to associate that tool with??

 

Next, you bust out my favorite part, the PHP. You establish that the variable queryValues is an array....understood. Then you crank out a foreach loop which will capture everything thats been stored in our tools array (which is all the tools we have selected) and store them in the variable itemID. Now this is really where the confusion returns for me. The line '$quantity = (int) $_POST['quantity'][$itemID];' is one I have never seen. Doing research I understand its some sort of count function, but I can't honestly say I get how it works. Then you run an if statement which basically says, if there is any time the itemID belongs to the quantity field that we are capturing && that there was actually some data in it, then do this next part?? Is that correct? Anywho, after that if statement if verified as 'yes, its greater than 0', you do another line of code that, once again, I don't understand how it works....quite frankly, here is where it gets completely dark for me. I don't understand what any of the remaining code is doing.

 

So there you have it...my version of what's going on is probably no where near correct. Below I have a couple direct questions along with the questions I have asked in the above recap of events. I know this is asking a lot, but it would be amazing (if you wouldn't mind) if you could answer these questions/explain this stuff to me.

 

1.) Can I just simply change the tool ID (ex. hammerID) to just the name of the tool (ex. hammer) ??

2.) What is the point of the array function in the textfield input? You call the value of the checkbox hammerID and then call the name inside the array hammerID. I don't think I understand this part, you mind explaining?

Link to comment
Share on other sites

Rather than respond to all of your comments I will provide my own explanation of the code. But, first let me answer your two specific questions.

 

1.) Can I just simply change the tool ID (ex. hammerID) to just the name of the tool (ex. hammer) ??

2.) What is the point of the array function in the textfield input? You call the value of the checkbox hammerID and then call the name inside the array hammerID. I don't think I understand this part, you mind explaining?

 

1. Yes. But, if you are properly constructing your database, the tools should be in a separate table with a unique ID for each record. Then that ID would be used as a foreign key to reference the tools from other tables.

 

2. See explanation below.

 

OK, I don't think you even need the checkboxes (as I explained earlier), but it sounds as if that is what you want to do. So, I will explain that code.

 

The form (modified to not use an ID value for the tools):

<input name="tools[]" type="radio" value="Hammer" /> Hammer
<input name="quantity[Hammer]" type="text" />

<input name="tools[]" type="radio" value="Wrench" /> Wrench
<input name="quantity[Wrench]" type="text" />

 

In the form you have separate checkboxes to select each tool and a corresponding text field to record the quantity for each tool. The name of each checkbox is "tools[]" with the value being the name of each tool. By naming the fields in this manner, the PHP code in the receiving page can reference the selected tools using $_POST['tools']. Note; only the values of the CHECKED checkboxes are passed in the POST data. So, on the receiving page, the variable $_POST['tools'] will be an array of all the checked tool inputs.

 

The quantity fields are named in the manner "quantity[TOOL_NAME]" where TOOL_NAME is the name of the tool. So, in the receiving PHP page you can reference the quantities in the format $_POST['quantity']['TOOL_NAME']. Now, since you have a list of all the selected tools in the $_POST['tools'] array, you just iterate through that array to find the associated quantity values.

 

PHP Processing page (minor modification to use the tool name instead of ID)

$queryValues = array();
foreach($_POST['tools'] as $tool)
{
    $quantity = (int) $_POST['quantity'][$tool];
    if($quantity > 0)
    {
        $queryValues[] = "($tool, $quantity)";
    }
}
$query = "INSERT INTO [table_name] (`toolname`, `toolvalue`)
          VALUES " . implode(", ", $queryValues);

 

The first thing we do is create an array ($queryValues) to hold the values to be inserted into the database. The reason for this is that you should NEVER run queries in loops. Instead gather all the data in the loop and run one query. So, I will store a separate piece of text in this array for each record to be inserted in the DB.

 

Next, we will loop through each of the selected tools from the POST data and process that tool and it's associated quantity to create the values for the insert query. Within the loop $tool will be set as each selected tool name during each iteration.

 

Within the loop, we will first get the associated quantity for the selected tool. The (int) will ensure the value is converted into an integer. This serves two purposes 1) It ensure the value is a number and 2) it ensures the value will be safe for a DB query. Then there is an if statement to ensure the value is greater than 0. If 0 is an allowed value for your purposes, you can remove the IF statement.

 

If the quantity is valid we then add a new piece of text to the $queryValues array that will be used to insert a record in the DB. I assumed that the records being inserted will have (at a minimum) values for two columns: the tool name and the tool quantity.

 

lastly, after the foreach() loop completes, we have an array containing multiple records to be inserted into a table. So, we create a single INSERT query that will insert ALL the record in ONE query. This is done by imploding the records.

Link to comment
Share on other sites

You ever consider being a teacher??? That explanation was spot on. I understand it in its entirety. Thanks for taking the time to explain.

 

The query you are running has implode() which you state handles inserting multiple records into the database. Lets assume I want to record the 5 pieces of data into that field. 2 of which are captured on the form, and 3 that we define in our PHP. For this example I will say:

 

$variable1 = 1;

$variable2 = 2;

$variable3 = 3;

 

How would we also add this information to our database?

 

Also, I notice you have the following

 

implode('', '', $variable)

 

What is the purpose of the 2 null values?

 

Once again thanks for the previous explanation.

Link to comment
Share on other sites

...you are running has implode() which you state handles inserting multiple records into the database

 

Not quite. The implode merely formats the text for multiple records into a format so we can generate a single query for inserting multiple records. As I said previously you never want to run queries in a loop (i.e. inserting one record on each iteration of the loop).

 

Lets assume I want to record the 5 pieces of data into that field. 2 of which are captured on the form, and 3 that we define in our PHP.

I think you meant to say you want to store five pieces of data in the RECORD - not the field. And, further, you want three of those pieces of data to be the same for ech record inserted. In that case you just need to modify the loop that creates the $queryValues something like this:

        $queryValues[] = "($tool, $quantity, $variable1, $variable1, $variable1)";

Of course you would need to modify the query to include those three additional fields.

 

Also, I notice you have the following

 

implode('', '', $variable)

 

What is the purpose of the 2 null values?

There are no NULL values. Implode simply concatenates the values of an array. The first parameter defines the string that will be used between each each value. In the code I provided I am creating an array where each value in the array represents the complete contents of one record to be inserted into the DB. I then use implode to format those values into the proper format to insert multiple records in one query.

 

Here is a simple query to insert ONE record int he db

INSERT INTO table (field1, field2)
VALUES (value1, value2)

 

Here is how you format a query to insert multiple records at once

INSERT INTO table (field1, field2)
VALUES (valueA-1, valueA-2), (valueB-1, valueB-2), (valueC-1, valueC-2)

Link to comment
Share on other sites

Wow I didn't know you replied. You REALLY should consider being a teacher, you explanations make more sense than anything I have read on any forum to date. Thanks again bro, your method really just helped me with a large percentage of my project.

 

SOLVED.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.