PHP - Dynamic Form From Array. Or Better Solution ????
Hi all.
I am currently trying to build a site that will allow users to manage a self build house project. This is my first php MySQL project but I am getting to grips with it ok. I am currently building this for my own benefit at the moment as I am about to undertake a self build. I have a few questions to put to you guys. This is where I am at the moment I have a database table named materials which contains a list of materials , quantities, unit of measurement, id. My site has a user control panel that has separate forms for each stage of the build where the user enters the quantities of the materials, and the data is displayed as an array for each stage. So, heres question 1. I want to take the data and use it to generate a form which will be completed by several merchants.... so it will display similar to the array but will be a form with a text box for price where the merchant will insert a price. i.e <?php mysql_connect ("localhost", "test", "test") or die ('I cannot connect to the database becuase: ' . mysql_error()); mysql_select_db ("matquant"); // query $query = mysql_query("SELECT * FROM `quantites` ORDER BY `id` ASC"); // results while ($row = mysql_fetch_array($query)) { echo "<br />" .$row ['id']. " " .$row ['material']. " " .$row['quantity']. " " .$row['unit']. "<br />";} echo mysql_error(); ?> I want to add a text input box form which will allow the merchant to add a price to each item that is added to the array. so there the merchant will be able to give me a price for all the items in my list. Heres where I get stuck.... as I am constantly adding to the list I have no fixed amount of items so the form for the merchants needs to be built dynamically, ie each time I add a new material, I want the merchants form to get a new input. I am not very good at describing my problems but I am hoping that someone can help me out from the information given. Thats the first question. i like to get issues sorted in small bites. the second is the next big bite, I want to send the form above to several merchants, so I intend to have a user database with a user for each merchant, and link the tables so that each merchant can provide a price for each material, ideally the form would highlight the materials that have not had a price yet. I'm looking for advice on the best method of doing this basically but if I can get the first question sorted that would be great.. I have the test site local but can upload it it to the server if it will help you see what im trying to do. Any help that anyone can give will be greatly appreciated. Similar TutorialsIn brief, I'm attempting to capture the form data from a dynamic form to a mysql database. From he
To He
The post data looks like this from the form - Array(
... ) PHP CODE:
... As a non-php or mysql developer, I'm learning on the fly. This is a section of the php file that I was using to post the form data to mySQL. This worked great up to the point I added the dynamic form widget. <?php // This function will run within each post array including multi-dimensional arrays function ExtendedAddslash(&$params) { foreach ($params as &$var) { // check if $var is an array. If yes, it will start another ExtendedAddslash() function to loop to each key inside. is_array($var) ? ExtendedAddslash($var) : $var=addslashes($var); unset($var); } } // Initialize ExtendedAddslash() function for every $_POST variable ExtendedAddslash($_POST); $submission_id = $_POST['submission_id']; $formID =$_POST['formID']; $ip =$_POST['ip']; $fname =$_POST['fname']; $lname =$_POST['lname']; $spousename =$_POST['spousename']; $address =$_POST['address'][0]." ".$_POST['address'][1]." ".$_POST['address'][2]." ".$_POST['address'][3]." ".$_POST['address'][4]." ".$_POST['address'][5]; ... $db_host = 'localhost'; $db_username = 'xxxxx'; $db_password = 'xxxxx'; $db_name = 'xxxxx'; mysql_connect( $db_host, $db_username, $db_password) or die(mysql_error()); mysql_select_db($db_name); // search submission ID $query = "SELECT * FROM `tableName` WHERE `submission_id` = '$submission_id'"; $sqlsearch = mysql_query($query); $resultcount = mysql_numrows($sqlsearch); if ($resultcount > 0) { mysql_query("UPDATE `tableName` SET `fname` = '$fname', `lname` = '$lname', `spousename` = '$spousename', `address` = '$address', WHERE `submission_id` = '$submission_id'") or die(mysql_error()); } else { mysql_query("INSERT INTO `tableName` (submission_id, formID, IP, fname, lname, spousename, address) VALUES ('$submission_id', '$formID', '$ip', '$fname', '$lname', '$spousename', '$address') ") or die(mysql_error()); } ?> It has been suggested that I explore using the PHP Explode() function. It's possible that may work, but can't get my head around how to apply the function to the PETLIST Array. Looking for suggestions or direction to find a solution for this challenge. Looking forward to any replies. Hi all, I would like to ask you if somebody could have a better idea to build this function. The current one is working, but I feel this built a bit in an amateur manner. Feel free to add your ideas so we can learn more about PHP and how to deal with arrays.
I have an array: $arrayVideoSpecs = Array( Array( 'aspect' => '4:3', 'density' => '442368', 'resolution' => '768x576' ), Array( 'aspect' => '4:3', 'density' => '307200', 'resolution' => '640x480' ), Array( 'aspect' => '16:9', 'density' => '2073600', 'resolution' => '1920x1080' ), Array( 'aspect' => '16:9', 'density' => '121600', 'resolution' => '1280x720' ) );
and I want an array as output grouped by video aspect ratio where the key is the pixel density and the value is the video resolution, namely like that for aspect ratio 16:9 ... Array ( [2073600] => 1920x1080 [121600] => 1280x720 )
Then I coded this function which is working but seems amateur ... function groupAndExtractByAspect($array, $groupBy, $aspect, $density, $resolution) { $groupByAspect = Array(); foreach ($array as $value) { $groupByAspect[$value[$aspect]][] = Array($value[$density], $value[$resolution]); } $arrayClean = Array(); foreach ($groupByAspect as $key => $value) { if ($key == $groupBy) { $arrayClean[$key] = $value; } } foreach ($arrayClean as $aspectGroup) { $arrayOutput = Array(); for ($i = 0; $i <= count($aspectGroup); $i++) { $densityIsValid = false; $resolutionIsValid = false; if (!empty($arrayClean[$groupBy][$i][0])) { $density = $arrayClean[$groupBy][$i][0]; $densityIsValid = true; } if (!empty($arrayClean[$groupBy][$i][1])) { $resolution = $arrayClean[$groupBy][$i][1]; $resolutionIsValid = true; } if (($densityIsValid === true) && ($resolutionIsValid === true)) { $arrayOutput[$density] = $resolution; } } } return $arrayOutput; }
The usage is as follow ... $showArray = groupAndExtractByAspect($arrayVideoSpecs, '16:9', 'aspect', 'density', 'resolution'); echo '<pre>'; print_r($showArray); echo '</pre>';
Thank you very much for your ideas! Mapg Hi guys, I'm using the API for Remember the Milk through a PHP class that I found online called PHP-RTM. Anyway after so much headaches (the authentication for the Remember the Milk API is one of the hardest I've ever come across) I've finally connected everything and gotten to the stage that I have some raw data inside an array. The next step is to work with that data. Basically I want to access the names of the task in a complex multi demensional array and I have no idea how to do this. I have done a var_dump of the array I am working with to show you the complexity. Just remember that in the complex var_dump below there are only 4 tasks: array(2) { ["stat"]=> string(2) "ok" ["tasks"]=> array(2) { ["rev"]=> string(31) "nxeir6vy9pcgcggoss4wwwooc8cwo8w" ["list"]=> array(3) { [/tt][list][li][tt]=> array(2) { ["id"]=> string( 8) "13927305" ["taskseries"]=> array(2) { [/tt][/li][li][tt]=> array(11) { ["id"]=> string(9) "104056511" ["created"]=> string(20) "2011-02-02T12:48:48Z" ["modified"]=> string(20) "2011-02-02T12:48:48Z" ["name"]=> string(42) "Send confirmation email to luxury car hire" ["source"]=> string(13) "iphone-native" ["url"]=> string(0) "" ["location_id"]=> string(0) "" ["tags"]=> array(0) { } ["participants"]=> array(0) { } ["notes"]=> array(0) { } ["task"]=> array(9) { ["id"]=> string(9) "156815180" ["due"]=> string(20) "2011-02-02T13:00:00Z" ["has_due_time"]=> string(1) "0" ["added"]=> string(20) "2011-02-02T12:48:48Z" ["completed"]=> string(0) "" ["deleted"]=> string(0) "" ["priority"]=> string(1) "N" ["postponed"]=> string(1) "0" ["estimate"]=> string(0) "" } } [1]=> array(11) { ["id"]=> string(9) "104148150" ["created"]=> string(20) "2011-02-03T01:25:57Z" ["modified"]=> string(20) "2011-02-03T01:26:17Z" ["name"]=> string(40) "Confirm that post has been sent with DVD" ["source"]=> string(2) "js" ["url"]=> string(0) "" ["location_id"]=> string(0) "" ["tags"]=> array(0) { } ["participants"]=> array(0) { } ["notes"]=> array(0) { } ["task"]=> array(9) { ["id"]=> string(9) "156951316" ["due"]=> string(20) "2011-02-02T13:00:00Z" ["has_due_time"]=> string(1) "0" ["added"]=> string(20) "2011-02-03T01:25:57Z" ["completed"]=> string(0) "" ["deleted"]=> string(0) "" ["priority"]=> string(1) "N" ["postponed"]=> string(1) "0" ["estimate"]=> string(0) "" } } } } [1]=> array(2) { ["id"]=> string( 8) "13925842" ["taskseries"]=> array(12) { ["id"]=> string( 8) "98105089" ["created"]=> string(20) "2010-12-19T11:25:25Z" ["modified"]=> string(20) "2011-02-02T13:01:42Z" ["name"]=> string(25) "Read for one hour per day" ["source"]=> string(13) "iphone-native" ["url"]=> string(0) "" ["location_id"]=> string(0) "" ["rrule"]=> array(2) { ["every"]=> string(1) "1" ["$t"]=> string(21) "INTERVAL=1;FREQ=DAILY" } ["tags"]=> array(0) { } ["participants"]=> array(0) { } ["notes"]=> array(0) { } ["task"]=> array(9) { ["id"]=> string(9) "156576423" ["due"]=> string(20) "2011-02-02T13:00:00Z" ["has_due_time"]=> string(1) "0" ["added"]=> string(20) "2011-02-01T13:01:45Z" ["completed"]=> string(0) "" ["deleted"]=> string(0) "" ["priority"]=> string(1) "N" ["postponed"]=> string(1) "0" ["estimate"]=> string(0) "" } } } [2]=> array(2) { ["id"]=> string( 8) "17007566" ["taskseries"]=> array(11) { ["id"]=> string(9) "104017503" ["created"]=> string(20) "2011-02-02T05:45:04Z" ["modified"]=> string(20) "2011-02-03T02:29:55Z" ["name"]=> string(96) "Hook up watermark for both videos (check email) and send to Rachelle and Steve at compare quotes" ["source"]=> string(2) "js" ["url"]=> string(0) "" ["location_id"]=> string(0) "" ["tags"]=> array(0) { } ["participants"]=> array(1) { ["contact"]=> array(3) { ["id"]=> string(7) "2150286" ["fullname"]=> string(10) "Samuel Nam" ["username"]=> string(10) "samuel.nam" } } ["notes"]=> array(0) { } ["task"]=> array(9) { ["id"]=> string(9) "156754354" ["due"]=> string(20) "2011-02-02T13:00:00Z" ["has_due_time"]=> string(1) "0" ["added"]=> string(20) "2011-02-02T05:45:04Z" ["completed"]=> string(20) "2011-02-03T02:32:00Z" ["deleted"]=> string(0) "" ["priority"]=> string(1) "N" ["postponed"]=> string(1) "0" ["estimate"]=> string(0) "" } } } } } } Anyone know the code i can use to simply get the "name" keys from the complex array below. I've created a movie to show what I'm trying to achieve, please click below to view: http://screenr.com/XIY MOD EDIT: formatted text to get rid of errant smilies . . . [/list] okay I am using a jquery plugin to re-arrange images which are in mysql and they have their own "order_number" ... when i re-arrange stuff the new order is put into a hidden field in a form and i have it along with another hidden field with their current order... when submitted I combine these two fields in an array so the key is the original order and the value is the new order ....i have 12 images... Array ( [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 [11] => 11 [12] => 12 ) this is what is what the array looks like... i have a foreach loop with a mysql query but things get kind of weird when you try to do it this way $num = $_POST['old_num']; $num = unserialize($num); $sort = $_POST['sortOrder']; $sort = explode(',', $sort); if ($_POST){ $combine = array_combine($num, $sort); foreach($combine as $key => $value){ mysql_query("UPDATE shirts SET order_number='$value' WHERE order_number='$key' ") or die(mysql_error()); } when you do this lets say for example we have the image with order number "1" get switched with the image order number "2"..... the database first updates with number 1 which becomes 2... then when it goes to number "2"... at this point... the first image gets switched back to number 1.... so 1 becomes 2 then the new 2 becomes 1 again and the other 2 becomes 1 also. I can not think of another way I could update mysql with the correct order numbers... If anyone has any ideas or other solutions I am open to all suggestions... thank you! Ok I have a form that will include some text boxes and two sliders where numbers can be selected. When a user clicks submit I want it to take them to a solutions page based on what numbers they have selected. I'm finding it hard to explain what I'm trying to do so heres an example of what I would like. http://www.cleardebt.co.uk/#help It will be a form like that which links to a solution. If someone could please tell me what I need to do or have a tutorial of something similar it would be a great help for me to start. I have users in my database with many stored points ie age, gender, interests etc. about 20 points in all.
I have a table of products that I want to recommend only applicable products. They each have saved like minage, maxage, gender, interest etc for the ideal consumer. ie dress gender=f
This is the bare bones of what I have so far:
$result = mysql_query("SELECT * FROM user_table WHERE hash='$session_id'"); $rowuser = mysql_fetch_array($result); $result = mysql_query("SELECT * FROM products"); $rowproducts = mysql_fetch_array($result);So now I have $rowuser['gender'] = m , how do I remove all from $rowproducts where gender = f? Is there a best way to do this knowing I have about 20 points to go through before I am left with an array with just the best selection of products for this user in it? i want to make a forum that nobody can fill that through any software automatically i make this one with java script authentications but some one also make a break of this and and he fill this software only in one click with automatic way this one which i make http://www.ebs-ads.com/advertising/forms.php?id=4&name=Abel any better solutions using php or any other function that users must have to post every input field separately manually ..if yes Please suggest me thanks Hello all, I have yet again trouble finding a logical solution to my problem. I'm fetching an array which can hold 1 or more values. The problem is, I want these values to ouput in my json_encode function, but this also needs to happen dynamically depending on the amount of values. I can't explain it further, so here's the code so far: Code: (php) [Select] $files = mysql_fetch_array($get_files); $a = count($files); $i = 1; while ($files) { $variablename = 'fileName' . $i; $$variablename = $files['fileName']; $i++; } $output = array( OTHER VALUES , 'fileName1' => $fileName1, 'fileName2' => $fileName2, 'fileName3' => $fileName3, ............); // How do I add the fileNames dynamically depending on how many there are? This got me thinking, I also need to dynamically GET the values with jQuery. How would I do that, when the above eventually works? Thank you. Hi, Is there any way to pass dynamic arguments to array_multisort. Below is my idea of what the code should look like. First it has the data then its builds an array of array indexes with the sort direction. This array is then passed to the array_multisort function with the original data. Code: [Select] $data[] = array([0] => 67, [1] => 2, [3]' => 2001); $data[] = array([0] => 86, [1] => 4, [3]' => 2002); $data[] = array([0] => 98, [1] => 5, [3]' => 2002); $data[] = array([0] => 86, [1] => 6, [3]' => 2003); $data[] = array([0] => 67, [1] => 1, [3]' => 2004); $arg = array(1 => SORT_ASC, 3 => SORT_DESC); array_multisort($arg, $data); I have got this working with hardcoded values, for example... Code: [Select] array_multisort($sort1, SORT_ASC, $sort3, SORT_DESC, $data); but in my code instead of just 2 sorts there could be 'x' amounts. I hope ive made this clear. Any response would be much appreciated. Thanks in advance. Hi ! I'd like to count all occurences in "$thiscodestring" into a "dynamic?" array and print it out after the end of the loop, how do I assign the variablenames dynamically ? $query = "SELECT codes, status FROM table"; while ($row = mysql_fetch_assoc($result)) { $thiscodestring = $row[codes]; // looks like "a1 c2 d3 10 15 1 a1 a1"; $singlecodes = explode(" ", $thiscodestring); foreach($singlecodes as $thiscode) { $$thiscode[count] = $$thiscode[count] + 1; } } After all Mysql-Stuff is done I'd like to print out the counted codes, for example the code "a1" was found 100 times in all querys then $$a1[count] should be 100, c2 was found 15 times, then $$c2[count] should be 15 and so on. Question: How do I tell php to assign a "dynamic" variable with the name of the found string which was exploded (in this example a1, c2, d3... ) before ?! $$ does not seem to work. And how can I then print_r() the value if I dont know the name ? Thanks ! How can I use php to update a dynamic amount of input fields and tell mysql which ones to update respectively? Essentially I have a list of occupations and if someone wants to update one of them I don't know how to tell php which one they've changed in a dynamic way. Code: [Select] <?php if(!empty($occupations)) { ?> <h3 id="job_function">Job Functions</h3> <?php $i = 0; foreach($occupations as $occupation) { ?> <div class="formElement"> <div class="formFieldLabel "> <label for="occupation_<?php echo $i; ?>"><?php echo $occupation['companyname']; ?></label> </div> <div class="formField"> <input id="occupation_<?php echo $i; ?>" type="text" name="occupation_<?php echo $i; ?>" value="<?php echo $occupation['function']; ?>" /> </div> </div> <?php $i++; } } ?> I'm scraping a housing website with html source: Code: [Select] <tr><td> </td><td> Bedrooms </td><td> </td><td >3</td><td> </td></tr> <tr><td> </td><td> Full Baths </td><td> </td><td >1</td><td> </td></tr> <tr><td> </td><td> Partial Baths </td><td> </td><td >1</td><td> </td></tr> <tr><td> </td><td> Interior Sq Ft </td><td> </td><td >1,356</td><td> </td></tr> <tr><td> </td><td> Acres </td><td> </td><td >0.16</td><td> </td></tr> What i'm trying to do is create an associative array with only the details I want from the above. I've already got a function that steps through the HTML and creates an array element for each row with the contents of each <td> statement as follows: Code: [Select] $repl = array(" ", "(", ")"); $repl_with = array("", "", ""); foreach ($rows_feat as $id2 => $row2){ $features_raw = $scrape->fetchAllBetween('<td','</td>',$row2,true); //$features_data[str_replace($repl,$repl_with,strtolower(trim($features_raw[1])))] = trim($features_raw[3]); $countid=$countid+1; } The array produced by this would look like: features_raw[1] = Bedrooms features_raw[3] = 1 Basically, I want to take data like this: Beds 1 Baths 1 Garage Yes and create an array on the fly: House[beds]=1 House[baths]=1 House[garage]="yes" The problem is that the order of Beds, Baths and Garage changes. So on some house pages the order would be Baths, Garage, Beds.. etc. Any pointers out there? Thanks, Brett Okay, so I have a page with a heap of fields and buttons on it (and want to keep it like that really) inside one form. Layout Box 1 Button 1 Box 2 Button 2 Box 3 Button 3 Box 4 Button 4 etc... Box 1 is called 'amount1$id' Box 2 is called 'amount.$id' where $id is the $id of the data being displayed etc So a sample form may look like Box: "amount22" Button: "Pay22" Box: "amount25" Button: "Pay25" Box: "amount32" Button: "Pay32" Box: "amount39" Button: "Pay39" Box: "amount420" Button: "Pay420" Its working fine up to that point. My problem now is that I can't work out how to get that id number from the form once submitted. If I could get the button name somehow I could do it, although I don't know the button or box names when writing the processing script. I could use a loop and check if button1 to buttonX was posted etc, although if there is a large number of entries in the database, then that starts to become a problem. Thoughts? Hi all, it's been a while since I wrote in PHP but a University project has forced me to touch up on my knowledge of it. I'm trying to re-create an old form making system I made a few years ago from memory. But it's not working. I know it's something very obvious but I just need another eye to take a look for me. I get the following error message: Warning: Invalid argument supplied for foreach() in /home/birdneto/public_html/rebelfrogv2/p_createaccount.php on line 169 So I know it's do with my show_form(); function. Can anyone help? Code: [Select] <div id="page-body-special"> <?php // List page details $page_header = "Create your account"; $page_desc = "Enter your details below to create an account. Creating an account comes with great benefits! You can create a wishlist, sign up for our mailing list and purchase items. Make sure you enter all your information correctly."; // List form details $form_name = "createaccount"; // List all the field names here $field_email_address = "email_address"; $field_email_address_confirm = "confirm_email_address"; $field_password = "password"; $field_password_confirm = "confirm_password"; $field_house_number = "house_number"; $field_street_name = "street_name"; $field_city = "city"; $field_county = "county"; $field_postcode = "postcode"; $field_phone_number = "phone_number"; $field_newsletter = "newsletter"; $field_submit = "submit"; // Define all the field meta data (field name, maxlength, minlength, field type, [field options], [field description]) $fields = array( array($field_email_address, 80, 8, "text", $_POST[$field_email_address]), array($field_email_address_confirm, 80, 8, "text", $_POST[$field_email_address_confirm]), array($field_password, 16, 8, "password", $_POST[$field_password]), array($field_password_confirm, 16, 8, "password", $_POST[$field_password_confirm]), array($field_house_number, 2, 4, "password", $_POST[$field_house_number]), array($field_street_name, 16, 8, "password", $_POST[$field_street_name]), array($field_city, 16, 8, "password", $_POST[$field_city]), array($field_county, 16, 8, "password", $_POST[$field_county]), array($field_postcode, 16, 8, "password", $_POST[$field_postcode]), array($field_phone_number, 16, 8, "password", $_POST[$field_phone_number]), array($field_newsletter, 0, 0, "checkbox", $_POST[$field_newsletter], 0, "Would you like to sign up to our newsletter?"), array($field_submit, 0, 0, "submit", "Create Account") ); // Check if form has been submitted or not. All fields must be declared here with an if statement if($_POST['submit']) { // Set no_errors and show_form to inital 0 $no_errors = 1; function show_errors($field) { if($field == $field_email_address) { if(strlen($_POST[$field_email_address]) < $fields[0][2] and strlen($_POST[$field_email_address]) > $fields[0][1]) { $no_errors = 0; $error = "Your email address must be between " . $fields[0][2] . " and " . $fields[0][1] . " characters"; } } if($field == $field_email_address_confirm) { if($_POST[$field_email_address_confirm] != $_POST[$field_email_address]) { $no_errors = 0; $error = "Your emails do not match each other"; } } if($field == $field_password) { if(strlen($_POST[$field_password]) < $fields[2][2] and strlen($_POST[$field_password]) > $fields[2][1]) { $no_errors = 0; $error = "Your password must be between " . $fields[2][2] . " and " . $fields[2][1] . " characters"; } } if($field == $field_password_confirm) { if($_POST[$field_password_confirm] != $_POST[$field_password_confirm]) { $no_errors = 0; $error = "Your passwords do not match"; } } if($field == $field_house_number) { if(strlen($_POST[$field_house_number]) < $fields[4][2] and strlen($_POST[$field_house_number]) > $fields[4][1]) { $no_errors = 0; $error = "Your house number must be between " . $fields[4][2] . " and " . $fields[4][1] . " numbers"; } } if($field == $field_street_name) { if(strlen($_POST[$field_street_name]) < $fields[5][2] and strlen($_POST[$field_street_name]) > $fields[5][1]) { $no_errors = 0; $error = "Your street name must be between " . $fields[5][2] . " and " . $fields[5][1] . " characters"; } } if($field == $field_city) { if(strlen($_POST[$field_city]) < $fields[6][2] and strlen($_POST[$field_city]) > $fields[6][1]) { $no_errors = 0; $error = "Your city must be between " . $fields[6][2] . " and " . $fields[6][1] . " characters"; } } if($field == $field_county) { if(strlen($_POST[$field_county]) < $fields[7][2] and strlen($_POST[$field_county]) > $fields[7][1]) { $no_errors = 0; $error = "Your county must be between " . $fields[7][2] . " and " . $fields[7][1] . " characters"; } } if($field == $field_postcode) { if(strlen($_POST[$field_postcode]) < $fields[8][2] and strlen($_POST[$field_postcode]) > $fields[8][1]) { $no_errors = 0; $error = "Your postcode must be between " . $fields[8][2] . " and " . $fields[8][1] . " characters"; } } if($field == $field_phone_number) { if(strlen($_POST[$field_phone_number]) < $fields[7][2]) { $no_errors = 0; $error = "Your phone number must be under " . $fields[7][2] . " numbers"; } } return $error; } if($no_errors == 0) { show_form(); } else { echo "<p>Form posted</p>"; echo $br . $br; } } else { show_form(); } function show_form() { // Show the page header echo $br . '<form method="post" action="./?p=' . $page . '" name="' . $form_name . '">'; echo $br . $br; echo '<table id="form-' . $form_name . '">'; echo $br; // List all fields in form format foreach($fields as $meta) { // Explode the array and implode it, changes commas to spaces, then makes all words have capital letters $label_exp = explode("_", $meta[0]); $label_imp = ucwords(implode(" ", $label_exp)); // Is the field type a submission? if($meta[3] == "submit") { echo ' <tr><td colspan="2"><input type="' . $meta[3] . '" name="' . $meta[0] . '" class="' . $meta[0] . '" value="' . $meta[4] . '" /></td></tr>'; echo $br; } // Is the field type a select? elseif($meta[3] == "select") { $options = explode(",", $meta[5]); echo ' <tr><td><label>' . $label_imp . '</label></td><td><select type="' . $meta[3] . '" name="' . $meta[0] . '" class="' . $meta[0] . '">'; echo $br; foreach($options as $option) { function is_selected() { if($option == $_POST[$meta[0]]) { echo 'selected="selected"'; } } echo(' <option ' . is_selected($option) . '>' . $option . '</option>'); echo $br; } echo ' </select></td></tr>'; echo $br; } // Is the field type a checkbox? elseif($meta[3] == "checkbox") { echo ' <tr><td><label>' . $meta[6] . '</label></td><td><input type="' . $meta[3] . '" name="' . $meta[0] . '" class="' . $meta[0] . '" /></td></tr>'; echo $br; } // Is the field type anything else? else { echo ' <tr><td><label>' . $label_imp . '</label></td><td><input type="' . $meta[3] . '" name="' . $meta[0] . '" class="' . $meta[0] . '" maxlength="' . $meta[1] . '" value="' . $meta[4] . '" /></td></tr>'; echo $br; } } // Show the page footer echo '</table>'; echo $br . $br; echo '</form>'; echo $br . $br; } echo $br . "<h1>" . $page_header . "</h1>"; echo $br . $br; echo "<p>" . $page_desc . "</p>"; echo $br . $br; echo '<div class="clear"></div>'; echo $br . $br; ?> </div> hi i am trying to make a payroll calculator script that takes employee info, calculates pay, displays submitted info in a table, stores info in an array, and updates the array when new info is submitted. i have most of these accomplished, i am having trouble with the "store into an array, and update the array when new info is submitted" parts of the project. i am still not very fluent in php so there may be easier ways to achieve what i have so far. any pointers would be a great help, this part has got me stumped.
Hi All, $userClient = "VARIABLE OF WHO IS LOGGED IN"; <form action="actions/assign.php" method="post"> <?php $sql = "SELECT * FROM Engineers where Engineer_Company = '".addslashes($userClient)."' and userType = '5'"; $result = mysqli_query($db, $sql); while($row = mysqli_fetch_assoc($result)) { $userSID = $row["userID"]; echo '<tr> <td>'.$row["userName"].' <input type="hidden" class="form-control" id="usersID[]" name="usersID'.$row["userID"].'" value="'.$row["userID"].'"> <input type="hidden" class="form-control" id="date" name="date" value="'.date('d-m-Y').'"> </td> <td>'; $sql1 = "SELECT * FROM job_orders where companyID = '".addslashes($userClient)."'"; $result1 = mysqli_query($db, $sql1); echo "<select style='width: 250px;' id='job$userSID' name='job$userSID'>"; echo '<option value="">-- Please Select --</option>'; while($row1 = mysqli_fetch_assoc($result1)) { echo '<option value="'.$row1["jobID"].'">'.$row1["jobtitle"].'</option>'; } echo "</select>"; echo '</td> <td>'; $query = $db->query("SELECT * FROM Engineer_Company WHERE Company_ID = '".addslashes($userClient)."'"); $rowCount = $query->num_rows; if($rowCount > 0){ echo ' <select name="company'.$userSID.'" id="company'.$userSID.'" style="width: 250px;"> <option value="">-- Select Company --</option>'; while($row = $query->fetch_assoc()){ echo '<option value="'.$row['Engineer_Company_ID'].'" class="form-control form-control-sm">'.$row['Engineer_Company_Name'].'</option>'; } echo '</select>'; } echo'</td> <td> <div class="form-group"> <select id="site'.$userSID.'" name="site'.$userSID.'" style="width: 250px;"> <option value="">-- Select Site --</option> </select> </div> '; echo'</td> </tr>'; echo ' <script type="text/javascript"> $(document).ready(function(){ $("#company'.$userSID.'").on("change",function(){ var diag_id = $(this).val(); if(diag_id){ $.ajax({ type:"POST", url:"ajax-client-side.php", data:"diag_id="+diag_id, success:function(html){ $("#site'.$userSID.'").html(html); } }); } }); }); </script>'; } ?> </tbody> </table> <input class="btn btn-dark float-right" type="submit" value="Allocate"> </form>
Hi, i am creating a web application, and i would like some help/advise on how to tackle a problem. I need to make an image i have into a contact form, with four fields, which basically posts information into a database. I am not sure how i would go about doing this as i will need to make each of the fields dynamic to post the data. I have attached the image to make my point a bit clearer. thanks So I know a little about PHP but I am no expert by any means. But I have a project that I am working on for a fantasy football league and need some help. My users pick players from a list and then their selections are put into a database. So more than one user is likely to pick the same player. Then I need to score the players based off their games for the week. So I have code that gets the Distinct PlayerID and creates a form to update the player score (see code below), but I have no idea how to process the form. It's a little more complicated then the forms I've used before because the MySQL query would need to UPDATE all the rows for each individual PlayerID. Am I making any sense? Anyway, here is the code. If anyone has suggestions on how to process this form or a better way of doing it then please let me know. <? print '<form id="form1" name="form1" method="post" action="update_player.php">'; // Connecting, selecting database $link = mysql_connect('localhost','user','pass'); if (!$link) { die('Could not connect: ' . mysql_error()); } //Query $query=mysql_query("select DISTINCT(PlayerID), PlayerName, Team From fantasy4.temp ORDER BY Team;") or die ('Could not connect: ' . mysql_error()); print' <center> <table align=center border=0 cellpadding=0 cellspacing=2 width=350> <tr align=center> <td width=50 align=center><b>Player ID </b></td> <td width=50 align=center><b>Team</b></td> <td width=200 align=center><b>Player Name</b></td> <td width=50 align=center><b>Score</b></td> <tr><td colspan="10" bgcolor="black" height="1"></td></tr> '; while($row=mysql_fetch_array($query)){ if($color == 1) { print '<tr bgcolor=#dDdDdD> <td align=center> ' . $row['PlayerID'] . ' </td> <td align=center> ' . $row['Team'] . ' </td> <td align=center> ' . $row['PlayerName'] . ' </td> <td align=center> <input name="' . $row['PlayerID'] . '" type="text" id="' . $row['PlayerID'] . '" size="5" maxlength="5" /> </td> </tr>'; $color=0; } else { print '<tr> <td align=center> ' . $row['PlayerID'] . ' </td> <td align=center> ' . $row['Team'] . ' </td> <td align=center> ' . $row['PlayerName'] . ' </td> <td align=center> <input name="' . $row['PlayerID'] . '" type="text" id="' . $row['PlayerID'] . '" size="5" maxlength="5" /> </td> </tr>'; $color=1; } } print '</table>'; print '<input type="submit" name="button" id="button" value="Update Player Scores" /></form>'; ?> This is what I tried that did not work <? // Connecting, selecting database $link = mysql_connect('localhost','user','pass'); if (!$link) { die('Could not connect: ' . mysql_error()); } //Query $query=mysql_query("select DISTINCT(PlayerID) From fantasy4.temp;") or die ('Could not connect: ' . mysql_error()); while($row=mysql_fetch_array($query)){ $PlayerID = $_POST[$row['PlayerID']]; } while($score = array($_POST['$PlayerID'])){ //Insert Query $query2=mysql_query("UPDATE fantasy4.temp set Score='$score' where PlayerID='$PlayerID'") or die ('Yikes could not connect: ' .mysql_error()); $result = @mysql_query($query2); } //Check whether the query was successful or not if($result) { header("location: register-success.php"); exit(); }else { die("Query failed - " .mysql_error()); } ?> First off thank you for opening my issue and taking the time out to try and help. I have created a php page that will display a list of people from a mysql database. What i would like to do is have a button that will update a field in the database when pressed. My question is if i make the fields into a form will it only update that one person? Hi - I have a form which is populated with values from a DB. This is done by looping through the DB values using a foreach. It works fine. I populate my form with those values. However, I want to be able to amend those values, and then submit the new values back to the DB with 1 single submit button. I don't want a separate submit button for each row of my form. The problem is that because the form is built with a foreach, as the it loops through the variables on each pass of the DB, only the final row of DB are present in the form variables. Question: My 'foreach' approach must be faulty. What is the mechanism or approach I need to use to update the values from the whole form ?? MANY THANKS for all your help !! |