Let user create table based on existing table - php

After registering at my site, I want the user to select some elements from a table that already exists in my DB, and add them to "their" column in another table.
Say this is the existing table in a MySQL DB:
ID Item Color
1 Car Red
2 Apple Green
3 Trophy Gold
4 Suit Black
I would want the user to fill out a form where they:
Are presented with a dropdown list, to choose items from (based on the existing table).
When they have chosen up to x amount of items, they submit their "inventory" which..
Adds the selected items to their own column in a table that holds "user_inventory"
So this second table (user_inventory) should look something like this:
User_id item_id1 item_id2 item_id3
1 4 3 1
2 3 1 4
3 2 4 1
4 2 4 3
I don't expect you to write the code for me or anything, but I would be thrilled if you could answer these questions:
Is this possible?
Can you direct me to a similar type of thread or article that helps me write the code?
If you can not direct me anywhere, please help me in whichever way you see fit.

It is possible.
Firstly, read from the "existing" db table to create the select menu, example:
<select name="item">
<?php
$sql = "SELECT * FROM existing";
$query = mysqli_query($mysqli, $sql);
while ($result = mysqli_fetch_array($query)) {
$item = $result['item'];
echo "<option value='$item'>$item</option>";
}
?>
</select>
This will create the "Item" select menu, I'm sure you can figure out how to do the other menus by yourself, all that is left now is to submit and store into the new table which I assume you already know how to do.
if(isset($_POST['yoursubmitname'])) {
$item = $_POST['item'];
/// RUN THE INSERT COMMAND HERE //
}

Related

create an event on PhpMyAdmin

i have a table named request where i store name, last name,user_id, category amount and points. its a money request i made so amount can vary all the time.
and i have a table named user. that stores user id, category, name, last name
what i want to accomplish is create an event that triggers everyday at 23:00 and search for all user based on there category and update the table user if it finds any user category with he following condition.
category id 1,2,3 all user at the begin are 1, if user category is 1 and points are = 4000 then update table user by changing user category to 2 example
<?php
$points = data->info_from_db;
$user_category = data->info_from_db;
if ($user_category == 1 && $points == 400)
{
///update users set category ='2'
}
else {
echo "no update today";
}
?>
this can be done by php? all i need is to first get all sum(points) of each user and their category and update if the condition is true.

checkbox inputs and DB search

I'm tagging Movies and store this into a Database.
a tag_id could be a car, train, boat and details could be color or specific types.
DB
movie_id | tag_id | tag_detailsid
2612 | 75 | 1
2612 | 10 | 3
2612 | 12 | 2
The tags are submitted via a form with checkboxes (all checkboxes checked are added to the db)
Now..
How do I keep track with checkboxes I uncheck..at a later stage
So looking at the above example.. for movie_id 2612, I uncheck tag 12 with id 2 as details.
So $_POST holds only 75-1 and 10-3....12-2 should be deleted from dB.
So I thought.. I simply go through the dB with a while loop and compare the db value with the values I get from the checkboxes (via the $_Post method)..
I count the values in the $_Post and it shows 2 (checkboxes checked).
Database however holds 3 entries ($numberofrecords) for that specific Movie.
My script so far...
$sql_query = "Select tag_id, tag_details_id FROM movie_tags WHERE movie_id = '2612";
$report = MYSQL_QUERY($sql_query);
$numberofrecords = mysql_num_rows ($report);
while ($report_row = mysql_fetch_array($report))
{
$thistag_id = $report_row['tag_id'];
$tag_details_id = $report_row['tag_details_id'];
foreach($_POST as $checkbox_id => $value)
{
if ($thistag_id == $checkbox_id) // check if DB tag equals checkbox value
{
echo "checkbox value is checked equals value in DB";
}
}
}
How do I track the record I need to delete from the database?
Sometimes the easiest solution is the way to go.
Unless you have a compelling reason NOT to, you can simply delete all of the tag records before saving, then insert only those that were checked:
sample code using OP's selected db driver
$sql = 'DELETE FROM movie_tags WHERE movie_id=2612';
mysql_query($sql);
foreach($_POST as $checkbox_id => $value) {
// save your records here
// To show you the code I'd need to see the HTML for the checkboxes.
}
NOTE: You should not be using mysql_. Use PDO / mysqli instead: Why shouldn't I use mysql_* functions in PHP?
A simple solution would be to delete every rows based on your primary key such as movie_id in your case and do insert in loop for every checked checkboxes. That is:
Delete rows based on movie_id
Loop through POST data and do insert

track selecting and unselecting an option When updating a table

I have three tables (I simplified it in this question) :
Table 1
id | Name
-----------
1 | John
2 | Smith
Table 2
id | Title
-----------
1 | Developer
2 | Web Developer
3 | A New Title
Table 3 (links between 1 and 2)
idName | idTitle
-----------
1 | 1
1 | 2
2 | 1
My problem is with the update page. My HTML is <select multiple> ... options ... </select> and I am using chosen to select and deselect options. I am trying to do this with PHP only.
Lets say that we have the following scenario:
The administrator wanted to remove the 'Developer' Title for 'John' and add 'New Title' for 'John'.
He/She will deselect Title id 1 and select id 3. When He/She submits the form I will get two select values: id 1 (the one that he selected) and id 2 (the one that was already there). But I will not get id 3 because he deselected it.
What I am struggling with is : when the user posted the new selected values the ones that were deselected were not submitted with the form. There is no way for me to track the ones that were deselected so I can delete them from my table. How do you update your table with the new changes then? Do you delete what is already existed in that table and add the ids again? Is there a better option?
UPDATE :
It seems #wander answer is less destructive than the other ones. However, #wonder did not explain how to compute step 4 in his answer. to distinguesh between new selected options, already existing selected options, and deselected options.
There's no need to submit the deselected one. e.g.
John has two titles(Developer and Web Developer) saved in database.
The administrator opens the page, selects 'New Title', deselects 'Developer' and clicks submit.
Now on server side, we can get
the title list of John stored in database: Developer and Web Developer
title list submitted from the users: Web Developer and New Title
We compare the two title lists and figure out: we shall delete Developer title and add New Title on John.
You could add hidden fields before the select menu which will cause 0/falsey values to also be sent to PHP.
<input type="hidden" name="stuff[]" value="0" />
<input type="hidden" name="stuff[]" value="0" />
<input type="hidden" name="stuff[]" value="0" />
<select multiple name="stuff[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
This is similar to how you would send unchecked check boxes to the server:
https://stackoverflow.com/a/1992745/268074 (note the answer without JS)
You can dump your old values in a hidden select, so you'll get them when handling your form.
<!-- Invisible select field -->
<select multiple name="oldData[]" style="display:none;" aria-hidden="true">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3" selected>3</option>
</select>
<!-- Real select field -->
<select multiple name="data[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Note: I was inspired by #Petah's answer, don't forget to upvote him :-).
Let's say we have $old_titles list with titles from db, and $new_titles titles from submit.
$add = array_diff($new_titles, $old_titles);
$delete = array_diff($old_titles, $new_titles);
$add - list of titles to add, $delete - list of titles to delete.
Add action:
$dbh->prepare('INSERT INTO table3(idName, idTitle) VALUES (:idName, :idTitle)');
foreach($add as $titleId) {
$dbh->execute(['idName' => $userId, 'idTitle' => $titleId]);
}
Delete action:
$dbh->prepare('DELETE FROM table3 WHERE idName = :idName AND idTitle = :idTitle');
foreach($delete as $titleId) {
$dbh->execute(['idName' => $userId, 'idTitle' => $titleId]);
}
Not sure why everybody keeps using hidden input fields to track the existing data. When you POST your form, you can just retrieve the original values from the database. That's a lot safer then depending on user input, because even hidden fields can be altered. I know it won't matter too much in this particular situation, but I think it's best to always use the best practise.
Now in PHP you have two options. The first would be to delete all relations and then add the new relations. The second would be to delete all that wasn't posted and add/update the relations that where.
Although the second options might seem to be the "least destructive" as you call it, it is the easiest and least error prone way. The only reason I would abandon this tactic is when I would store extra data in the relations table. EG: date added (when did somebody get into a function) or added by user.
How would you go about it (method 2)?
Keep in mind that I use a method that tries to continue whenever possible. Another approach would be to halt when false data is posted.
<?php
if (array_key_exists("relations",$_POST) && is_array($_POST["relations"])) {
//no duplicates, you dont want to store the same function twice
//only integers
$list = array_unique(array_filter($_POST["relations"], "is_int"));
$csv = implode(',', $list);
//get the userid hoewever you normally would
$userId = 1
//Delete existing
$query = "DELETE FROM Table3 WHERE idname=".$userId
//insert all posted functions
//I select the id's from the actual table so it will never inserted a none existing ID.
//this approach never has duplicates, so the duplicate check in the beginning is redundant now, but I leave it incase I change this.
$query = "INSERT INTO Table3 (idName, idTitle) SELECT ".$userId.", Id FROM Table2 WHERE id IN (".$csv.")".
//execute queries
} else {
//nothing posted, delete all relations
}
?>
Now if you only want to insert new data and remove none-existing
<?php
if (array_key_exists("relations",$_POST) && is_array($_POST["relations"])) {
//no duplicates, you dont want to store the same function twice
//only integers
$list = array_unique(array_filter($_POST["relations"], "is_int"));
$csv = implode(',', $list);
//get the userid hoewever you normally would
$userId = 1
//Delete existing
$query = "DELETE FROM Table3 WHERE idname=".$userId." AND idTitle NOT IN (".$csv.")"
//only insert new functions
//I select the id's from the actual table so it will never inserted a none existing ID.
//this approach never has duplicates, so the duplicate check in the beginning is redundant now, but I leave it incase I change this.
$query = "INSERT INTO Table3 (idName, idTitle) SELECT ".$userId.", Id FROM Table2 WHERE id IN (".$csv.") AND id NOT IN (SELECT idTitle FROM table3 WHERE idName=".$userId.")".
//execute queries
} else {
//nothing posted, delete all relations
}
?>
The only better way is the simplest one, remember KIS
on update you just need to do following
DELETE FROM table3 WHERE idName=??
and then insert all selected idTitles again in table3
This can be done in two SQL statement without knowing which value has been de-selected. Following these 2 steps
1) In your PHP, create a comma separated list of all selected option. For example: 2, 3.
2) Then execute the following statements:
DELETE FROM tblLink WHERE idName = $id AND idTitle NOT IN ($list);
INSERT IGNORE tblLink (idName, idTitle)
SELECT $id, id FROM tblTitle WHERE id IN ($list);
Note: for shake of simplification, I use $id and $list in my example. When you intent to use it, you should properly prepare and bind parameter properly. Make sure that idName and idTitle are primary key to make it work.
To my opinion you have to check what actions should be performed first. This is a small example that you can run here http://sandbox.onlinephpfunctions.com/code/0fa11b3c9f846e344c912f5a3e994eea5e9cac34.
First run a select on Table 3 for idName=1 the output would be an array of idTitle's (1,2). In the following example the $array1 is the output of such a select statement and $array2 is the array of new idTitle's for the same idName that will have to be updated or deleted or inserted. If for example the new idTitles for a user are more or less than the previous ones then there you should have some sort of control over it in order to decide what queries you will run to the database.
$array1 = array(1,7,3,5);// initial idTitles try it on the above link (php sandbox) with more or less values
$array2 = array(1,4,3,6);//new idTitles try it on the above link (php sandbox) with more or less values
$count1=count($array1);
$count2=count($array2);
$diff=$count1-$count2;
if ($diff==0) {
$result1=array_values(array_diff_assoc($array2,$array1));
$result2=array_values(array_diff_assoc($array1,$array2));
$countr=count($result1);// or $result2 it is the same since they have the same length
$cr=0;
while($cr < $countr) {
print_r("update tblname set val=$result1[$cr] where id=theid and val=$result2[$cr]\n");
$cr++;
}
}
if ($diff!=0) {
$result1=array_diff($array2,$array1);
$result2=array_diff($array1,$array2);
if(count($result2)>0) {
foreach($result2 as $r2) {
print_r("delete from tblname where id=theid and val=$r2\n");
}
}
foreach($result1 as $r1) {
print_r("insert into tblname where id=theid and val=$r1\n");
}
}
How I would do it would extend the 1st table
id | Name | Title IDs
1 | John | 1,2
2 | Smith | 1,3
Each time the row is updated I would simply just replace the title_ids fields and be done with it.

Dynamic addition of details in sql from PHP

I was coding a script for the following model:
Suppose there are 5 events. For the users to register for the events, they need to input some details. Registration is in the form of a team, but the number of members in each event are different.
In my sql table events there is a row members which stores the number of members for all the 5 events.
Using the data stored in the members row, I can run a for-loop for the HTML display of table, where the user can input his and his team details.
But I'm confused as to how I will code the php part? I know php, getting the information and storing them in the sql database, but in this particular case do I have to code separate php script for all the events as the number of members will not be the same.
EDIT#1
The events are for example. :
**event1**: number of members: 5 (mem_1, mem_2, mem_3, mem_4, mem_5)
**event2**: number of members: 3 (mem_1, mem_2, mem_3)
**event3**: number of members: 2 (mem_1, mem_2)
**event4**: number of members: 4 (mem_1, mem_2, mem_3, mem_4)
**event5**: number of members: 6 (mem_1, mem_2, mem_3, mem_4, mem_5, mem_6)
The mem_x fields store the name of the member.
So how can I code a single php script for the registration. Do I have to make separate functions for all the events as the number of members are different for the events.
You check the inputted data to make sure that the number of members entered matches the number of members allowed for the event.
Then you loop over the data adding each (new) member to your members table, and the member_id and event_id to your members_events junction table (adding a number of rows equal to the number of members).
If it were me, I'd have my table with the following fields:
Column Name Example Value
member_id [auto increment]
member_group Step1
member_type text
member_order 1
member_title First Name
member_field_name fname
member_default enter first name
member_max_length 25
Then, in PHP, you can do a query like:
$fields = mysql_query("Select * From [member table] Where member_group = 'Step1' Order By member_order;")
while ($field = mysql_fetch_assoc($fields)) {?>
<label for="<?= $field['member_field_name']; ?>">
<?= $field['member_title']; ?>
<? switch ($field['member_type']) {
case "text":
echo "<input type=\"text\" name=\"".$field['member_field_name']."\" value=\"".$field['member_default']."\" />";
break;
}?>
</label>
<?}
Then, when processing the page, just get the list of fields again from the database (for the field name) and process the page.
You don't need different functions depending on the number of members.
You could for example store all the inserted members in an array and then do something like
foreach($members as $member){
mysql_query ( "INSERT INTO members (name,eventID) VALUES (".$member['name'].",".$members['eventID'].")" );
}
where $members is the array containing the members names.
Is this what you wanted to know?

One Article multiple categories system in PHP SQL

Multiple categories selection system for Article
Earlier M using two tables
articles & categories and save category ID in articles table
But in this system I can save only one category ID per article
I want to save Article in Multiple categories
While searching I found same question on StackOverflow
I understand the whole concept of adding one more table of relationship & saving Article ID & Category ID in this table.
But not aware how to implement multiple selection system using arrays in New Article Form & Edit Article Form.
earlier I am showing Select in my form to display categories list in Add Article & Edit Article Page.
pls someone explain me How to show categories list in multiple checkbox style in my form so user can select multiple categories and then after POST how to get checkbox data and run query to insert data in both Article Table & New Relationship table with selected categories ID
want to display category List like this screenshot
Many Many Thanks...
EDIT:
I use echo '<input type="checkbox" name="selcats[]" value="$catid"> ' .$catname;
to display Categories check box
Its showing in a row side by side.
how to change display like screenshot i.e. list with scrollbar
& need to process this array and insert in new table while inserting article in databse.
EDIT 2
got the checkbox display correct in a scroll list by using a div :D
<div style="height: 150px; width: 200px; overflow: auto;">
In my case, I use a "tag system", for instance: You have an article with one category, nothing will change that... In adition, you can create another field in the article table with the relevant words (or whatever you want) and separete them with spaces or commas.
// Get the data from your database
$tags = 'world, travel, turism, cities';
// Separate the values
$tags = explode(", ", $tags);
// Create a link for each one
foreach($tags as $t)
{
echo ' ' . ucfirst($t) . ' ' . "\r\n";
}
It should output:
World
Travel
Turism
Cities
And it means that you can SELECT articles that have the title LIKE the tag, or whatever you want to search.
Is that what you was looking for?
You basically require two tables, with this structure
table_categories
_____________________________
| id | title |
-----------+---------------+
table_category_detail
______________________________________________
| id | categoryId | articleId |
-----------+---------------+------------------
To extract all categories, select all from the table_categories and put up into the select menu with mutiple selection enabled.
Next, when posted get the selected box values and insert into table_category_detail one by one
This is how you create a select box
$query = "SELECT * FROM table_categories";
$result = mysql_query($query);
echo '<select multiple="multiple">';
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['id'].'">'.$row['title'].'</option>';
}
echo "</select>";
Or a Multiple Check Box
while($row = mysql_fetch_assoc($result)) {
echo '<input type="checkbox" name="selcats[]" value="'.$row['id'].'"> ' .$row['title'];
}
After the post:
// Here write codes to insert the article first
$articleId = mysql_insert_id(); //get the id
$values = $_POST['selcats'];
foreach($values as $value) {
$query = "INSERT into `table_category_detail` VALUES(NULL, $value, $articleId)";
$result = mysql_query($result);
}

Categories