PHP MYSQL edit form, trying to implode/explode row to checkboxes? - php

I have a form that has multiple categories. They are separated by checkboxes, so one could check any number of categories that their post/story will be in.
The values are stored inside a db row separating them by commas while INSERT
GetSQLValueString(implode($_POST['r_category'],", "), "text"),
So in the database I could have an entry that looks like this:
2,3,6,12
Which those are category numbers.
I am now building an edit form feature to use to Edit and UPDATE these records. I can not find a way to "EXPLODE" the values into checkboxes on the edit form??
So if you log in and go to the ENTRY that you want to edit for example, I have Checkboxes separating the Categories, so it will be easy to check and uncheck to add and not add... I have tried everything I could to get the values to POST and be checked when viewing this Edit Form.
Here is an example of one of my Category Check boxes on my edit form page, but it is not working when I have multiple Categories, like the example above.. 2,3,6,12 ?? :
<input type="checkbox" name="r_category[]"
<?php if (!(strcmp("2", $row_Recordset2['r_category']))) {
echo "checked=\"checked\"";} ?> value="2" />Cat 2
Thanks in advance NINJAS!!

I can not find a way to "EXPLODE" the values into checkboxes on the edit form
This line is so close to the answer that I'm seriously wondering if this is a joke post.
Given your database structure as it is, you can use the explode() function to break the value into an array based on a delimiter. For example:
$values = "1,2,3,4";
$array_of_values = explode(",", $values);
After this, $array_of_values will contain an array of four elements with the values of 1, 2, 3, and 4 respectively.
When deciding whether or not to display the checkbox as checked, you can use the in_array() function to make that call:
if (in_array("2", $array_of_values)) {
echo 'checked="checked"';
}
Beyond that, let me take this opportunity to second what #MarkB said in the comments on this question: it's a bad idea to hold multiple values in a single database field. It makes searching for things harder, it makes adding values harder... it just makes everything more complex than it needs to be.
The best way to handle this would be to have a many-to-many table which stores rows of items and categories, with one row for each category that an item belongs to.
In other words, where you currently have this:
Item | Category
---------------
123 | 1,2,3,4
You would instead have a table that looks like this:
Item | Category
---------------
123 | 1
123 | 2
123 | 3
123 | 4

You can use it as shown below it could be helpful
if (in_array("2", $row_Recordset2['r_category'])) {echo "Checked";}

That in_array conditional never did work for me. I devised a totally front-end solution instead that works like a charm and automatically updates itself based on changes to the database. If you're interested, check it out here.
https://stackoverflow.com/a/26433841/1896348

Related

Go through result query without foreach loop

I am currently working on a project where it would come in handy to deal with a query result without having to use foreach loops to access everything of the array.
Let me explain it with an example:
I am selecting something from the database like
"SELECT * FROM table WHERE clientgroupid = 1"
The shown result is
name country phone clientgroupid
john america 12313 1
mike netherland 3123123 1
So I basically get 2 rows with that content as a result.
Now I would go on and run through that result array with a foreach and output it that way.
But that would limit my output to just 2 rows.
Which in the picture would result in the output of just enough input fields for 2 persons.
What I need is, that I show all results from the database in those input fields.
But there not "filled out" fields should be shown as well - in order to give the Moderator the posibility to fill it out to add more people to the database.
Please correct me if my way of thinking is completly off here - I welcome all suggestions or solutions
Thank you
EDIT
The issue is as following:
When I get 2 rows as a result from the database I would only create 2 lines of content like here :
But I also want to have all other input fields shown, so that the moderator can add more clients if needed.
So the output with 2 found Clients and rest empty fields would look like this:

Generic structuration of a web form and a MySQL's table for saving a array of undefined length

In a web form i will ask the user for their job experiences, this data will have no fixed lenght. I need to let the user insert all the items he needs, every item will content 3 fields; job title, description and year.
My firts problem is, how can i ask in the html form for the items? i mean, whats the best way to ask items with no fixed lenght using html/php (and maybe ajax)? I saw some sites that have a button (add one) when you hit it a new item slot is showed, but i have no idea of how to implement this, an example will be sufficient.
The second part is, how can i managed the data flow in post or get?, until now, i only use fixed fields, so i always know in my php script how many post or get vars i will get. How can i use multiple POST vars without knowing the amount of them?
And the last one (and the more important), how will be the best structure for my table in MySQL? If i get multiple items for a fixed table where i will have all my users, how can i resolve the multiple items issue? For example, if my table is:
User | password | job_experiences
admin | root | (this is just a cell, how can i save multiple items here?)
jonh | 1234 | (this is just a cell, how can i save multiple items here?)
Thanks for any help!!!!
Those are 3 questions, and it's best to post 3 questions, instead of discussing all of them. I will post the basics, and if you have specific questions, ask.
First, use button to add, and a JavaScript to clone an existing row (which can have more then one input field). For fieldnames use something like company_name[] - the [] is the important part, at this will send the field as an array. If you are editting profile, you can use company_name[$id] to preserve the mapping.
Second, in PHP you will receive this as $_POST['company_name'] which will be numeric array with all the company names. Or if you specify $id - with the corresponding keys. So, you have to loop trough all company_names, if there are other fields - you retrieve them the same way, using the current key. Example:
for (i =0; i<$_POST['comany_name'].length;i++) {
$company = $_POST['comany_name'][$i];
$start_year = $_POST['from'][$i];
...
}
Next, you need 1 table for the users (username, password), and another for job experiences (userid, company, description, from, to). This is called 1:M relation

Writing specific values to a database X times?

To begin with, i should clarify the title, so you really understand what I'm trying to do.
I'm working on a shopping-cart-ish script, but it's a little different because all products (almost always) will be purchased each time. Therefore i believe it's best to list all of the items up with a table, and then let the customer choose the amount of each product they want.
It'd look something like this:
-- Name ------------------------- Amount --
-- A random product ------------- 15 ------
-- Another random product ------- 2 -------
-- And a third one --- ---------- 19 ------
-- ------------------------------ ---------
-- ------------------------------ SUBMIT --
The problem is, I'm not sure how to write it into the database. Or more specific, i don't know how to submit the data in a way that i get all of the chosen products, as well as the amount of each one into an array. I might add more products to the database later, so i can't hardcode it in.
I can't post two values in one input, which is too bad. If i could do that i could post the ID and the amount as two different values.
Any ideas how to do this?
When you create your input fields, use an array for the name, with the product id as the key.
For example (where $product_id is the ID of the product that the amount corresponds to):
<input type="text" name="amounts[<?=$product_id?>]">
Then in PHP, after the form is posted, $_POST['amounts'] will be an array, where the keys are the product IDs, and the values are the actual amounts. You do not need to do anything special for this to happen; by default, PHP will recognize that GET/POST data that contains []s should be made into an array.
Then you can just iterate over this array to update the database:
foreach ($_POST['amounts'] as $product_id => $amount)
{
if (!empty($amount)) // was a value given for this amount?
{
// build your insert query here
}
}
concatenate the productID and the qty with a pipe "|" so it would be
productId=14
Qty= 3
inserted value= 14|3
then after your db fetch, you can explode the data by the "|" and have part1=14 and part2=3

Making a checkbox recognize its intended data

Level: PHP Learner
I'm stuck with a checkbox problem. I have a db that contains names and unique id numbers.
Using a query, I am pulling a selection of students and showing them to a user in an ultra simple HTML table on a form. Each row begins with a checkbox. The method is POST. So far, so good. My table looks like this:
+-----------+----------+----------+
| SELECT | NAME | ID |
+-----------+----------+----------+
| [] | John | 2233 |
+-----------+----------+----------+
| [] | Susie | 5577 |
+-----------+----------+----------+
[-SUBMIT-]
My problem is that I cannot seem to make the checkbox associate with each record's unique ID. Once the user has selected rows and clicked submit, the $_POST array remains empty.
None of my beginners books reference this specific issue. They go through the "regular" checkbox routines that don't involve interacting with rows from a db. I also could not find an issue on Stackoverflow that addresses this. Also tried Google: plenty of stuff on checkboxes, but I couldn't find any that helped me on this problem.
Just do something like this:
<input type="checkbox" name="ids[]" value="2233" /> ... rest of row
<input type="checkbox" name="ids[]" value="5577" /> ... rest of row
Now, in PHP, you can get the selected ids like this:
$ids = $_POST['ids'];
if( empty($ids) ) $ids = array();
This sets $ids to an empty array if the form was submitted without any of the checkboxes checked.
Edit: If your form doesn't get more complex as you describe, take Doug Neiner's approach, as it is way simpler. This approach is right if a table is likely to have a number of columns.
I like to do it this way:
Number the checkboxes sequentially (1 to 100) and add a hidden field connecting the row number to a real database ID:
<input type="checkbox" name="row_1" value="checked">`
<input type='hidden' name='row_1_id' value='2233'>`
Store the total number of rows in another hidden field
<input type='hidden' name='row_total' value='99'>
Then, in the receiving script, iterate from 1 to the total number of rows using for, check whether this row was selected, and get the associated database ID:
for ($i = 1; $i <= $number_of_rows; $i++)
{
if ($_POST["row_$i"] == "checked")
{
$database_id_unsafe = $_POST["row_{$i}_id"];
...
the latter, of course, needs to be properly sanitized and escaped in case it is processed further.

php dynamic checkboxes

Currently I have a form that submits an image with textfields such as
title, description and another field that autoincrements for imageID, another
area for the actual file , called vfile, and *** another part that has
3 checkboxes and a text field.
Everything works fine, and this is what it does. Submits the data to a database so that it can pull the information to a page on the website.
The only part I am trying to update is:
The 3 checkboxes and the textfield.
Lets say the first checkbox reads: Apples
The second : Oranges
The Third: Grapes
And in the other category is a blank textfield that if you add something, it would add it to a category called "Other".
So the database design has 4 fields: 1 - apples, 2 - oranges, 3 - grapes, 4 - other.
When I click a checkbox, it would add checked to the database under the correct one, either apples, oranges, or grapes.
If I add a field to the textbox such as: Bannanas, then it would add "Bannanas" to the database field vother and show that in the database.
This is all fine, but what if the next picture has all 4 items, plus another one? Such as if the next picture had Apples, Oranges, Grapes, Bannanas, and Plums?
How could I have the "Bannanas" other category, change into a checkbox category that could be chosen for the next pics when I go to the add images page next time.
So that when I go to the second picture to submit, it would give me the option of not just 3 checkboxes, but 4 checkboxes now, that I could check the first 4, "Apples, Oranges, Grapes, Bannanas" and then put Plums in the other category.
Basically upon submit it takes what is in the other feild and addes a new category to the database, which is then displayed in the array of checkbox choices and it is removed from the Other Category now, for it is a checkbox. (thus it would not want the value left in the old field, for it would keep creating the same category over and rewriting the old data possibly.
Anyway, any suggestions?
Thanks in advance.
(It sounds like this is more of a database design question and not a php question, but I may be misunderstanding what it is you are looking for advice on)
It sounds like you are saying that these attributes (Apples, Orange, etc) are stored as columns in your main table; but the situation you are describing sounds more like Tagging. Typically you would maintain a list of things that get tagged (your images), and a separate list of all possible tags (Which would be a table containing the rows : Apple, Orange, Grape). Your UI has the option to select from pre-existing tags (rows in the tag table) or add a new tag using the "Other" box. New tags would be added as a new row to the tag table. Since tags and tagged items have a many-to-many relationship you would create a third table (called a join table) that stores keys of tagged items and keys of tags; that way you can select either side of the relationship easily : get all the tags for a given item; get all the items with a given tag.
Does that help?
(EDIT : for comments)
So, Activities sounds like the list of Tags. If I want to show a form with checkboxes for all the Activities I can query the activities table for them. Each of those checkboxes can have a name attribute or something that captures the ID of the row that its bound to.
Also I would select from the join table the ids of the tags that my currently viewed image has selected. As I am populating the checkbox list I can check this result set to see if the id of the checkbox I'm putting on the page is in the list of tags for the image.
To store this back to the db on submit, the easiest thing is probably to (in a transaction) delete all the entries for the image from the join table and replace them with new entries based on the state of the check boxes in the form.
Drop the apples, oranges and grapes columns.
Create a second table with two fields: imageID and itemtype.
Don't make any of the two a key. Now you can list as many different types of items for each image as you need. It will be comparatively expensive to get the list of item types in use from the database but unless you have millions of items this shouldn't be a problem. (Mikeb is suggesting to keep the list of item types in use in a separate table to speed this up.)
The alternative is to dynamically add a column to the first table for each item type you encounter. This will create a very sparse table. I wouldn't do this.
You need to change your database schema to support an infinite number of attributes.
You should move your list of attributes from a set of fields in the record to a list of related records in a new table. This new table requires 2 columns. The first is the primary key from the existing table so you can establish the relationship between the tables. The second is the attribute field ('Bananas' or 'Apples' or 'Plums', etc.) You can have as many records in the attributes table as you like for each record in your main table. You could also have no attribute records if none are checked.
This kind of relationship between two tables is called a one-to-many relationship.

Categories