PHP - Post Data Updating Mysql Tables With One-to-many Relationship
Hi all
I have 3 tables Table_1, Table_2 and Table_3 Table_1 is a list of countries, with name and country_id Table_2 is a table that has 3 fields, id, name and description Table 3 is a table that has name, Table_2_id So what I need to do: Display the name and description field of Table_2 in a form Loop through the countries table and display each as an input box and display on the same form When I fill out the form details, the name/description must be inserted into Table_2, creating an id The input boxes data then also needs inserting into Table_3, with the foreign key of Table_2_id So a small example would be: Name: testing Description: this is a test Country of Australia: Hello Country of Zimbabwe: Welcome This means that in Table_2, I will have the following: ============================= | id | name | description | 1 | testing | this is a test ============================= Table_3 ============================= | Table_2_id | name | country_id | 1 | Hello | 20 | 1 | Welcome | 17 ============================= 20 is the country_id of Australia 17 is the country_id of Zimbabwe Code: Generating the input fields dynamically: $site_id = $this->settings['site_id']; $options = ''; $country_code = ''; $query = $DB->query("SELECT country_code, country_id, IF(country_code = '".$country_code."', '', '') AS sel FROM Table_1 WHERE site_id='".$this->settings['site_id']."' ORDER BY country_name ASC"); foreach ($query->result as $row) { $options .= '<label>' . 'Test for ' . $this->settings['countries'][$row['country_code']] . '</label>' . '<br />'; //$row['country_id'] is the country_id from Table_1 $options .= '<input style="width: 100%; height: 5%;" id="country_data" type="text" name="' . $row['country_id'] . '" value="GET_VALUE_FROM_DB" />' . '<br /><br />'; } echo $options; This outputs: Code: [Select] Textareas go here...... <label>Test for Australia</label> <input type="text" value="" name="20" id="country_data" style="width: 100%; height: 5%;"> <label>Test for Zimbabwe</label> <input type="text" value="" name="17" id="country_data" style="width: 100%; height: 5%;"> Now, I need to insert the value of the input field and it's country_id (20 or 17) into Table_3 and also Table_2_id. This then means I could get the value from Table_3 to populate 'GET_VALUE_FROM_DB' But I'm at a loss on how I'd do this. Could someone help me with this? Thanks Similar TutorialsHi,
I want each new incident created into the t_incidents table by the user to be associated with the AgencyID, a foreign key in the t_users table.
The problem is I do not know how this relationship will work and whether I will need a junction table.
The two tables a
t_Users +----------+----------+------------+ |UserID | AgencyID |User name | +----------+----------+------------+ |1 | 1 |john | +----------+----------+------------+ |2 | 1 |andrew | +----------+----------+------------+ t_Agencies +----------+------------+ |AgencyID |agency name | +----------+------------+ |1 |police | +----------+------------+ |2 |immigration | +----------+------------+I will appreciate your advice. Joseph Edited by josephbupe, 13 October 2014 - 03:04 AM. Ok, so I'm not quite sure how to explain this, but here it goes: I have table A that contains stats for all players in the NHL, and then I have table B with just a few players. These few players in table B are also in table A, but table B has more information on them. I want to take the stats for these players out of table A and put into table B, and I want table B to update along with table A every time those numbers change. How would I do this? I have a table for logins and a table for addresses. I'm using 1 form to create the username/password (which is being inserted into the "logins" database), and the persons name, address, etc. which is being inserted into the "addresses" database. What do I need to do to make it so that when a user log's in to the site and make's it to the checkout page, that their address is tied to their username? Ok, something I haven't done yet, I've programmed the majority of my site so far and have yet needed to utilize my relationships. Hopefully I set the tables up correct with foreign keys, primary keys, constraints, and references. This is what I need to do, should be relatively easy for most people here. I have one table... Friends with columns... friend_id - id of the friend users_id - id of the user who added the friend I have another table Statuses with columns... users_id - id of the user who posted the status statuses - the status posted whens - the time the status posted ------ I have statuses properly posting to a person's profile.php page but, I want the homepage of the site (same concept as Facebook) to post the status of your friends. I mean, what's the purpose of a status if your friends can't see them. ------ So, I need to somehow extract all of a users friends from the friends table, and use those friends to insert the statuses of friends on someone's homepage. Much help is greatly appreciated. If you wish to see how my tables are set up and if they are correct, that would be appreciated, just ask, and I'll go get my sql query of those tables for you to look at. THANKS! By the way, my site is at... http://inyoursocialnetwork.netne.net - the domain name and the site name are just temporary fill ins. If you have any ideas or suggestions for a good name, please, please, please let me know. It's driving me nuts I can't come up with a good name. I would prefer a short one. Shorter is easier to type and generally easier to remember. Hi, I am re-visiting my database table relationship for criminal incidents. Six tables are involved plus a junction table to make it seven tables in total. I need someone to review this relationship and advise whether or not it is correctly set up. The relationships are as follows: 1. A person can belong to more than one incident: t_persons (one-to-many) t)_incidents_persons 2. A person can only have one nationality by birth t_persons (one-to-one) t_countries 3. An agency can have more than one incident t_agencies (one-to-many) t_incidents 4. A status (e.g. closed incident) can belong to more than one incident t_status (one-to-many_ t_incidents 5. A keyword (i.e. offence type eg theft) t_offencekeywords (one-to-many) t_incidents This portion is kind of stumping me. Basically, I have a two tables in this DB: users and users_access_level (Separated for DB normalization) users: id / username / password / realname / access_level users_access_level: access_level / access_name What I'm trying to do, is echo the data onto an HTML table that displays users.username in one table data and then uses the users.access_level to find users_access_level.access_name and echo into the following table data, I would prefer not to use multiple queries if possible or nested queries. Example row for users: 1234 / tmac / password / tmac / 99 Example row for users_access_level: 99 / Admin Using the examples above, I would want the output to appear as such: Username: Access Name: Tmac Admin I am not 100% sure where to start with this, but I pick up quickly, I just need a nudge in the right direction. The code I attempted to create just shows my lack of knowledge of joining tables, but I'll post it if you want to see that I did at least make an effort to code this myself. Thanks for reading! Hello folks, I can not seem to find out why this code is not being executed properly. Basically, I'd like to edit Records, so I am using forms to retrieve data, make modifications then save them. Code: [Select] <?php //connection to db $results = mysql_query("SELECT * FROM crud WHERE id=".$_GET[id]."") or die (mysql_error()); $row = mysql_fetch_assoc($results); echo "<form action=\"\" method=\"POST\">"; echo "Year: <input type=\"text\" value=".$row['car_year']." name=\"car_year\" /> <br />"; echo "Make: <input type=\"text\" value=".$row['car_make']." name=\"car_make\" /> <br />"; echo "Model: <input type=\"text\" value=".$row['car_model']." name=\"car_model\" /><br /><br />"; echo "Description:<br /><textarea rows=\"15\" cols=\"60\" name=\"description\" />". $row['description']. "</textarea>"; echo "<br /><input type=\"submit\" value=\"save\">"; echo "</form>"; if ($_POST['save']) { $car_year = $_POST['car_year']; $car_make = $_POST['car_make']; $car_model = $_POST['car_model']; $description = $_POST['description']; // Update data $update = mysql_query("UPDATE crud SET car_year='$car_year', car_make='$car_make' car_model='$car_model', description='$description' WHERE id=".$_GET['id']."") or die (mysql_error()); echo 'Update successfull'; } ?> Please HELP!!!! I used to be good at this but I changed servers and everything is different... Heres my code so far: Code: [Select] <?php $rated=$_REQUEST['rated']; echo $rated; $rating=$_REQUEST['rating']; echo $rating; // Make a MySQL Connection mysql_connect("localhost", "********", "********") or die(mysql_error()); mysql_select_db("*********") or die(mysql_error()); $result = mysql_query("SELECT * FROM main WHERE username = '$rated'") or die(mysql_error()); $row = mysql_fetch_array( $result ); $votes = $db_field['$rating']; $newvotes = $votes + 1; echo $newvotes; mysql_query("UPDATE main SET $rating = '$newvotes' WHERE username = '$rated'"); ?> Whats going on here is the colomb that I want to update comes as a variable $rated (That works) and then the database selects the row to update with $username (That works) and gets the variable $newvotes by taking the original value of the data its about to update and add 1 to it (That works) Then it updates the field to $newvotes.... I don't know why the update won't go through... there are no errors....
I need help here. I am creating a system where the user will be able to update the product stock by uploading the stock of the products according to the id that has been assigned to the product.
I tried the code below but all i could not update my data into my database. And there's not error shown on my code. I do not know what is wrong with my codes. Please help me. <?php include 'conn.php'; if(isset($_POST["add_stock"])) { if($_FILES['product_file']['tmp_name']) { $filename = explode(".", $_FILES['product_file']['tmp_name']); if(end($filename) == "csv") { $handle = fopen($_FILES['product_file']['tmp_name'], "r"); while($data = fgetcsv($handle)) { $product_id = mysqli_real_escape_string($conn, $data[0]); $product_stock = mysqli_real_escape_string($conn, $data[1]); $product_status = 1 ; $query = "UPDATE products SET `product_stock` = '$product_stock', `product_status` = '$product_status' WHERE id = '$product_id'"; mysqli_query($conn, $query); } fclose($handle); header("location: upload-product.php?updation=1"); } else { echo '<script>alert("An error occur while uploading product. Please try again.") window.location.href = "upload-product.php"</script>'; } } else { echo '<script>alert("No file selected! ") window.location.href = "upload-product.php"</script>'; } } if(isset($_GET["updation"])) { echo '<script>alert("Product Stock Updated successfully!")</script>'; } ?> <div class="col-12"> <div class="card card-user"> <div class="card-header"> <h5 class="card-title">Update Product Stock</h5> <div class="card-body"> <div class="form-group"> <label for="file">Update Products stock File (.csv file)</label> <a href="assets/templates/product-template.xlsx" title="Download Sample File (Fill In Information and Export As CSV File)" class="mx-2"> <span class="iconify" data-icon="fa-solid:download" data-inline="false"> </a> </div> <form class = "form" action="" method="post" name="uploadCsv" enctype="multipart/form-data"> <div> <input type="file" name="product_file" accept=".csv"> <div class="row"> <div class="update ml-auto mr-auto"> <button type="submit" class="btn btn-primary btn-round" name="add_stock"> Import .cvs file</button> </div> </div> </div> </div> </form> </div> </div>
This is the template that i require user to key in and saved it in CSV format before uploading it. I have a photo album style gallery to build and i'm finding it dificult to list all the table names (these are names of photo albums) and then enter the data into a seperate query for each album name (these will change often so i cant keep updating the file as normal. this will then post all the data to the xml file and show the set of photos in the individual albums in a flash file. can anyone help me where im going wrong at all? <?php $dbname = 'cablard'; if (!mysql_connect('localhost', 'cablard', '')) { echo 'Could not connect to mysql'; exit; } $sql = "SHOW TABLES FROM $dbname"; $result = mysql_query($sql); if (!$result) { echo "DB Error, could not list tables\n"; echo 'MySQL Error: ' . mysql_error(); exit; } while ($row = mysql_fetch_row($result)) { echo "Table: {$row[0]}\n"; } mysql_free_result($result); $query = "SELECT * FROM photo ORDER BY id DESC"; $result2 = mysql_query ($query) or die ("Error in query: $query. ".mysql_error()); while ($row = mysql_fetch_array($result2)) { echo " <image> <date>".$row['date']."</date> <title>".$row['title']."</title> <desc>".$row['description']."</desc> <thumb>".$row['thumb']."</thumb> <img>".$row['image']."</img> </image> "; } ?> Thanks James so I'm trying to change some specific columns in a row in a table of a MySQL database by calling the Doctrine_Query when an option is selected inside an admin panel of my website. Here are the details: Table name: chatUsers I need to find all rows with the person who has a username of: $chatUsers->username (The column inside chatUsers is called username) Once all those rows are found, change the value of all the row's column "type" to "user" Is this even possible? So far I have: [/list] Code: [Select] <?php function userChatReset(){ $query = Doctrine_Query::create()->update('db_chatUsers')->set('type', 'user')->where('username = '.$chatUsers->username); //execute query $rows = $query->execute(); echo $rows.' rows updated'; } ?> ...And I'm not sure where to go from there, or if that's even correct. Sorry in advance, I'm not very good with PHP yet. I have the following code, and really can't see what is wrong with it. Any help would be great. <?php if (!mysql_connect('127.0.0.1', 'root', '')) { echo 'Could not connect to mysql'; exit; } $dbname = 'Requests'; $result = mysql_list_tables($dbname); if (!$result) { echo "DB Error, could not list tables\n"; echo 'MySQL Error: ' . mysql_error(); exit; } while($row2 = mysql_fetch_row($result)) { foreach ($row2[0] as $table_id) { $query = "SELECT * FROM $table_id"; $dbresult = mysql_query($query); // added code to use the tablename and select all records from that table // create a new XML document $doc = new DomDocument('1.0'); // create root node $root = $doc->createElement('mixes'); $root = $doc->appendChild($root); // process one row at a time while($row = mysql_fetch_assoc($dbresult)) { // add node for each row $occ = $doc->createElement($table_id); $occ = $root->appendChild($occ); // add a child node for each field foreach ($row as $fieldname => $fieldvalue) { $child = $doc->createElement($fieldname); $child = $occ->appendChild($child); $value = $doc->createTextNode($fieldvalue); $value = $child->appendChild($value); } // foreach } // while } } echo 'Wrote: ' . $doc->save("s.xml") . ' bytes'; // Wrote: 72 bytes ?> Guys, quick one. Im writing a script for a form to post info into a MySql table. Now rather than just having a single row for input I'd like to have lets say 10 rows, so I can add 10 records to the database. What I'm pondering is 2 things: 1: can i just repeat Code: [Select] <input type="text" name="opponent" size="27" /> over and over, or is it going to need its own name each time for example; Code: [Select] <input type="text" name="opponent2" size="27" /> <input type="text" name="opponent3" size="27" /> 2: when it comes to the processing script is it more economical to have the forms input field named the same over and over (if it IS possible) and if not whats the most econimcal way to code my Code: [Select] $opp= $_POST['opponent']; $query="INSERT INTO fixtures (match_date, season, opponent) VALUES ('$date', '$season', '$opp',)"; Your help and comments are appreciated as always guys Tom This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=305750.0 I can add and delete data from my table. Now I need to be able to change one or more fields in an entry. So I want to retrieve a row from the db, display that data on a form where the user can change any field and then pass the changed data to an update.php program. I know how to go from form to php. But how do I pass the data from retrieve.php to a form so it will display? Do I use a URL and Get? Can I put the retrieve and form in the same program? $post='{"cart_items":[{"configuration":{"price":100,"recharge_number":"9999999999"},"product_id":"999","qty":1}]}';i try this n reslut was :There are no valid items in cart: help me plz Edited by ShivaGupta, 30 November 2014 - 01:11 AM. As I am new to all this php, I need some help and/or ideas on how to code this little idea of mine: I have a database with a members table, I would like to create some Teams, and so I want too create a new table with the info for these teams. My problem is to set what team a member belongs too. My idea short Add a new column in the members area to hold the Id of the team this member belongs too. So if member 1000 sends a "join team link" too member 2000 the script needs to get the team id from member 1000 and add this id to member 2000. select teamid from members where id=1000 update teamid='same id as member 1000' where id='membersid' I hope this all makes sense, cause I am having a hard time trying to explain it. Hi, I want to loop out data from DB in <input> and change and update several posts at the same time. Can you give me a short example, how <input> and maybe foreach could look like? Thanks I am working on a php project in which players can equipt items from there inventory and it shows them there current stats. When players have decided to equipt an item they hit the submit button and the new stats should show. The issue I have is that the data is delaying in update such as: we have 10 strength we equipt a sword with +2 to strength and click submit it displays we have 10 strength we equipt a axe with +3 to strength and click submit it displays 12 strength we equipt a sword with +2 to strength and click submit it displays 13 strength we equipt a sword with +2 to strength and click submit it displays 12 strength .... my code is represented below <?php updateEquiptment(); require("playerInfo.php"); ?> <p title="This stat increases how hard you hit with weapons!">Strength:<?php echo $baseStrength + getModStrength() ?> </p> the functions updateEquiptment and getModStrength are in the playerInfo.php file and are shown like this: $user = $_SESSION['username']; $result = mysql_fetch_row(mysql_query("SELECT equiptment FROM warUsers WHERE name = '$user'")); $equiptment = explode(",",$result[0]); function updateEquiptment() { global $user; $result = mysql_fetch_row(mysql_query("SELECT equiptment FROM warUsers WHERE name = '$user'")) or die(mysql_error()); global $equiptment; $equiptment = explode(",",$result[0]); } //get there modified stats function getModStrength() { $total = 0; global $equiptment; foreach ($equiptment as $value) //loop through every item in the equiptment { if($value == 0 || $value == null) //if nothing is equipt go to the next loop continue; $result = mysql_query("SELECT * FROM items WHERE id = '$value'"); $item = mysql_fetch_row($result); $total += $item[4]; //get the items strength and add it to the total } return $total; } any help on the matter would be greatly appreciated |