PHP - Need Help Dealing With Input Array
Hi
I found a tutorial on dealing with databases he http://www.phpfreaks.com/tutorial/php-basic-database-handling It's great, except that I need it to do more than just a name; I need first, last, dob and email. I have it figured out how to order, insert and delete, but can someone help me figure out how to do the updating? The tutorial creates an array called cname and loops through it to do the update, but when I add more fields, it only holds the last fileds (emails in this case) I just need to be able to update all the fields for each user instead of just the name. Sounds easy but I've gotten nowhere Everything I have tried is posted below. Any help? Thanks Code: [Select] // INSERT: if we have a name to add... if($_POST['fname']) { // little bit of cleaning... $fname = mysql_real_escape_string($_POST['fname']); $lname = mysql_real_escape_string($_POST['lname']); $dob = mysql_real_escape_string($_POST['dob']); $email = mysql_real_escape_string($_POST['email']); // check for previous entry $sql_check = "SELECT id FROM test WHERE fname='$fname' AND lname='$lname'"; $res_check = mysql_query($sql_check, $conn) or trigger_error("SQL", E_USER_ERROR); if (mysql_num_rows($res_check) == 1) { while ($row = mysql_fetch_assoc($res_check)) { $id = $row['id']; } // update $sql = "UPDATE test SET Current=1 WHERE id='$id'"; $res = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); } else { // insert new name into table $sql = "INSERT INTO test (id, fname, lname, dob, email) VALUES ('', '$fname', '$lname', '$dob', '$email')"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); } } // end if // UPDATE: if we have name(s) to change... if($_POST['udata']) { /* // for each name to change... foreach ($_POST['udata'] as $input => $v) { echo "$input = $v<br />"; $sql = "UPDATE test SET "; foreach ($v as $id => $value) { echo "$id = $value<br />"; } $sql .= "WHERE ..."; } echo "<hr />$sql<hr />"; print_r($_POST['udata']); */ for ($i = 0; $i < count($_POST['udata']['fname']); $i++) { $fname = $_POST['udata']['fname'][$i]; echo "$i = $fname<br />"; } /* foreach($_POST['cname'] as $cid => $cname) { // little bit of cleaning... $id = mysql_real_escape_string($cid); $fname = mysql_real_escape_string($cname); $lname = mysql_real_escape_string($cname); $dob = mysql_real_escape_string($cname); $email = mysql_real_escape_string($cname); // update name in the table $sql = "UPDATE test SET fname = '$fname', lname='$lname', dob='$dob', email='$email' WHERE id = '$id'"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); } // end foreach */ } // end if // DELETE: if we have a name to delete... if($_GET['id']) { // little bit of cleaning... $id = mysql_real_escape_string($_GET['id']); // delete name from table $sql = "UPDATE test SET Current=0 WHERE id= '$id'"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); } // end if // ORDERBY: if one of the links was clicked.. if ($_GET['orderby']) { // make an aray of allowed names $allowed = array('id','fname', 'lname', 'dob', 'email'); // bit of cleaning... $order = mysql_real_escape_string($_GET['orderby']); // is it a valid column name? yes: use it. no: default to 'id' $order = (in_array($order, $allowed))? $order : "id"; // if no link clicked, default to 'id' } else { $order = "id"; } // end else // SELECT: get the list of names from database $sql = "SELECT id, fname, lname, dob, email FROM test WHERE Current=1 ORDER BY $order"; //$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); $result = mysql_query($sql, $conn) or die(mysql_error()); /**** end deal with the database ****/ /**** list everything out ****/ // list columns echo "<form action = '{$_SERVER['PHP_SELF']}' method = 'post'>\r\n"; echo "<table border = '1'>\r\n"; echo "<tr>\r\n"; echo "<td><a href = '{$_SERVER['PHP_SELF']}?orderby=id'>id</a></td>\r\n"; echo "<td><a href = '{$_SERVER['PHP_SELF']}?orderby=fname'>fname</a></td>\r\n"; echo "<td><a href = '{$_SERVER['PHP_SELF']}?orderby=lname'>lname</a></td>\r\n"; echo "<td><a href = '{$_SERVER['PHP_SELF']}?orderby=dob'>dob</a></td>\r\n"; echo "<td><a href = '{$_SERVER['PHP_SELF']}?orderby=email'>email</a></td>\r\n"; echo "<td>delete</td>\r\n"; echo "</tr>\r\n"; // loop through list of names while ($list = mysql_fetch_assoc($result)) { echo "<tr>\r\n"; echo "<td>{$list['id']}</td>\r\n"; echo "<td><input type = 'text' name = 'udata[fname][{$list['id']}]' value = '{$list['fname']}' />\r\n"; echo "<td><input type = 'text' name = 'udata[lname][{$list['id']}]' value = '{$list['lname']}' />\r\n"; echo "<td><input type = 'text' name = 'udata[dob][{$list['id']}]' value = '{$list['dob']}' />\r\n"; echo "<td><input type = 'text' name = 'udata[email][{$list['id']}]' value = '{$list['email']}' />\r\n"; echo "<td><a href = '{$_SERVER['PHP_SELF']}?id={$list['id']}'>delete</a></td>\r\n"; echo "</tr>\r\n"; } // end while // list input box for adding new entry echo "<tr>"; echo "<td bgcolor = 'gray'></td>\r\n"; echo "<td><input type = 'text' name = 'fname' /></td>\r\n"; echo "<td><input type = 'text' name = 'lname' /></td>\r\n"; echo "<td><input type = 'text' name = 'dob' /></td>\r\n"; echo "<td><input type = 'text' name = 'email' /></td>\r\n"; echo "<td bgcolor = 'gray'></td>\r\n"; echo "</tr><tr>\r\n"; echo "<td></td>\r\n"; echo "<td align = 'center'><input type = 'submit' value = 'submit' /></td>\r\n"; echo "<td></td>\r\n"; echo "</tr></table></form>\r\n"; /**** end list everything out ****/ Similar TutorialsHi All, I've a loop which creates an array as follows: $product_table[] = ['SKU' => $sku, 'Label' => $attribute_name, 'Value' => $term_obj->name ]; I'm then grouping the data by SKU code: #group the products by SKU $group_products = array(); foreach ($product_table as $element) : $group_products[$element['SKU']][] = $element; endforeach; Finally, I output the data: #output the data foreach ($group_products as $itemName => $rows) : echo '<tr>'; #echo '<td>', $element['SKU'], '</td>'; $i=0; foreach ($rows as $row) : $i++; #echo '<td>'. $row["SKU"]. '</td><td>'. $row["Label"]. '</td><td>'. $row["Value"]. '</td>'; if ($i == 1): echo '<td>'. $row["SKU"]. '</td><td>'. $row["Value"]. '</td>'; else: echo '<td>'. $row["Value"]. '</td>'; endif; #echo '<td>'. $row["Value"]. '</td>'; endforeach; echo '</tr>'; endforeach; ?> And looks like: Product code System Pack Quantity XT1CWH System 1 1 x 3m XT2CWH System 2 1 x 3m XT3CWH System 3 1 x 3m
This works perfectly fine. However, some products share the same SKU and therefore it causes an issue, like the below: Product code System Pack Quantity XT1CLWH System 1 8 x 3m System 2 8 x 3m System 3 8 x 3m Is there a way I can avoid this, so if perhaps creates the new row but shows the same SKU code? Many thanks So if I have this code (while working on my local machine )... Code: [Select] for ($i=1; $i<=15; $i++) { if ($timelimit == $i) { ${"time".$i}="selected='selected'"; } } <select name="timelimit"> <option value="1" <?php echo $time1;?>>1</option> <option value="2" <?php echo $time2;?>>2</option> <option value="3" <?php echo $time3;?>>3</option> <option value="4" <?php echo $time4;?>>4</option> <option value="5" <?php echo $time5;?>>5</option> <option value="6" <?php echo $time6;?>>6</option> <option value="7" <?php echo $time7;?>>7</option> <option value="8" <?php echo $time8;?>>8</option> <option value="9" <?php echo $time9;?>>9</option> <option value="10" <?php echo $time10;?>>10</option> <option value="11" <?php echo $time11;?>>11</option> <option value="12" <?php echo $time12;?>>12</option> <option value="13" <?php echo $time13;?>>13</option> <option value="14" <?php echo $time14;?>>14</option> <option value="15" <?php echo $time15;?>>15</option> </select> When I view the select menu in the browser, all but one of the options says "Notice: Undefined variable: time1 in C:\wamp\www\yyyyyy\create.php on line 112". It doesn't say this if I publish everything to the internet. So the question is, should I put code in to eliminate those Notices, or does it not matter. In other words, if I add this snippet below to declare all the other variables, it eliminates all the Notices. But is this necessary/good practice to do?.. Code: [Select] for ($i=1; $i<=15; $i++) { ${"time".$i}=""; } I'm kind of a beginner, but I really need this script and I'm not sure how quite to do it as needed... With some html forms I need it so you can type a name in then click submit, then (with php) it will save that text into a text file or something. Later, when I hit a different button it will randomly display one of those texts/names from before. I am using file_get_contents to get file off the internet for further processing but somtetimes there is error fetching that file off the web in which case it would be nice to try to reload it again but I am not sure what would be best way to do it? How can I jump back on error? I guess there would have to be some jump to label condition, but how do I implement this? This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=313673.0 <?php if ($beyondportal % 26 == 0 || $beyondportal == 0){ ?> MY CONTENT <?php } ; ?> This code compares my variable $beyondportal and if it is a multiple of 26 counting up from 0, it prints my content. This is great but sometimes the number comes up a negative that is a multiple counting down from 0 like -26, -52, etc.. if I could do the opposite of a modulus I would think it would work but I'm not sure how to in php. any suggestions? I am trying to create a website that after you receive an email you have to use the email address and password to confirm account. Then the next page allows you to change your password. I want to save the users email from the first page and use it in the SQL statement in the second page to locate the user in the DB and update the data. There must be some problem with the way I have my code logically set up. It will make it to the 2nd step but then it will go back to the main email confirmation page. <?php include('common.php'); include('db.php'); session_start(); session_register('umail'); session_register('password'); session_register('pwd1'); session_register('pwd2'); if(!isset($_POST['email']) && !isset($_POST['password'])) { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "BLOCKED URL"> <html> <head> This is a test of my patience</head> <meta http-equov="Content-Type" content="text/html; charset=iso-8859-1"/> </head> <body> <form method="post" action="<?=$_SERVER['PHP_SELF']?>"> Email: <input type="text" name="email" size="8" /> password:<input type="password" name="password" size="8" /> <input type ="submit" name ="submit" value ="submit" /> </form> </body> </html> <? exit; } else { $umail = $_SESSION['umail'] = $_POST['email']; $password = $_SESSION['password'] = $_POST['password']; dbConnect("web2"); $sql ="SELECT * FROM `user` WHERE email ='$umail'"; $result = mysql_query($sql); $row = mysql_fetch_assoc($result); if(!$result) error('Contact DB admin'); if($result='') error('not in db'); if($_SESSION['umail'] != $row['email'] && $_SESSION['password'] != $row['password']) error('Wrong email or password'); } if(!isset($_POST['pwd1']) && !isset($_POST['pwd2'])) { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "BLOCKED URL"> <html> <head> This is a test of my patience</head> <meta http-equov="Content-Type" content="text/html; charset=iso-8859-1"/> </head> <body> <form method="post" action="<?=$_SERVER['PHP_SELF']?>"> password: <input type="text" name="pwd1" size="8" /> password confirmation:<input type="password" name="pwd2" size="8" /> <input type ="submit" name ="submit" value ="submit" /> </form> </body> </html> <? } else { $pwd1 = $_SESSION['pwd1'] = $_POST['pwd1']; $pwd2 = $_SESSION['pwd2'] = $_POST['pwd2']; if($_SESSiON['pwd1'] == $_SESSION['pwd2']) { dbConnect("web2"); mysql_query("UPDATE user SET password ='$pwd1' WHERE email ='$umail'"); $sql="SELECT * FROM 'user' WHERE email='$umail'"; $result = mysql_query($sql); $row = mysql_fetch_assoc($result); if($_SESSION['pwd1'] != $row['password']) { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "(BLOCKED URl"> <html> <head> This is a test of my patience</head> <meta http-equov="Content-Type" content="text/html; charset=iso-8859-1"/> </head> <body> <form method="post" action="<?=$_SERVER['PHP_SELF']?>"> password: <input type="text" name="pwd1" size="8" /> password confirmation:<input type="password" name="pwd2" size="8" /> <input type ="submit" name ="submit" value ="submit" /> </form> </body> </html> <? } else { error(' the man'); session_unset(); session_destroy(); } } } ?> Hi
How can limit only required input fields cannot be empty.
<form name="test" method="post" action="test.php"> <label for="quest"> <input type="text" name="quest" /> <!-- REQUIRED --> </label> <label for="answers"> <input type="text" name="answers[]" /> <!-- REQUIRED --> </label> <label for="answers"> <input type="text" name="answers[]" /> <!-- REQUIRED --> </label> <label for="answers"> <input type="text" name="answers[]" /> </label> <label for="answers"> <input type="text" name="answers[]" /> </label> <label for="answers"> <input type="text" name="answers[]" /> </label> <label for="submit"> <input type="submit" name="submit" value="Submit" /> </label> </form>Following function working only on all empty input fields, i need help to enable button when required fields is not empty. $(document).ready(function() { var $submit = $("input[type=submit]"), $inputs = $('input[name=quest], input[name=answers[]]'); function checkEmpty() { // filter over the empty inputs return $inputs.filter(function() { return !$.trim(this.value); }).length === 0; } $inputs.on('keyup', function() { $submit.prop("disabled", !checkEmpty()); }).keyup(); // trigger an initial blur }); I am using Guzzle as a HTTP client, and the following script results in the following error: $response = $this->httpClient->request('GET', "http://$this->host:$this->port/query", ['query' => $data]); $body = $response->getBody(); $rs=json_decode($body, true); Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 136956008 bytes) in /var/www/vendor/guzzlehttp/psr7/src/Stream.php on line 80 What are the work arounds? Instead of trying to convert it into an array all at once, how can I do so in pieces? I know the expected format so it seems I will need to read just the appropriate amount of bytes and then decode parts at a time. Seems like a pain. Are there any classes designed to do so, or can any of the following Guzzle built in methods be used? Thanks Guzzle Response methods: __construct getStatusCode getReasonPhrase withStatus getProtocolVersion withProtocolVersion getHeaders hasHeader getHeader getHeaderLine withHeader withAddedHeader withoutHeader getBody withBodyGuzzle Body methods: __construct __destruct __toString getContents close detach getSize isReadable isWritable isSeekable eof tell rewind seek read write getMetadataHow can I check if the text entered in a textarea field equals the text I have stored in a mysql table? Code: [Select] $submitted_description = trim(mysqli_real_escape_string($db,$_POST['description'])); $query = "SELECT description FROM pets"; $result = $db->query($query); $row = $result->fetch_assoc(); $sql_description = $row['description']; Here's what they echo: Quote submitted_description: Testing...\r\n\r\n1\r\n\r\n2\r\n\r\n3 sql_description: Testing... 1 2 3 I tried adding the following to get rid of \r\n from $submitted_description but they both still don't equal but echo the same text. Code: [Select] $submitted_description = str_replace(array("\r","\n",'\r','\n'),' ', $submitted_description); They following code only matches when no spaces are entered in the textarea field. Code: [Select] if($submitted_description == $sql_description) { echo "Match!"; } else { echo "Don't Match!"; } How can this be done? I also tried adding nl2br() to both variables but that didn't work either. This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=347191.0 I have a mysql table like so ID OrderID Name Image CatalogID 1 1 test pic1.jpg 1 2 2 test2 pic2.jpg 1 3 1 test3 pic3.jpg 2 4 1 test4 pic4.jpg 3 5 1 test5 pic5.jpg 4 6 2 test6 pic6.jpg 4 7 3 test7 pic7.jpg 4 etc etc (1) I want to use up and down buttons so that the OrderID can be modified to reflect the users order preference, how would I code it so it changes all the OrderID values in the table as necessary to produce the correct order using the buttons, the only affected items each time would be the ones in the same CatalogID group. (2) How do I re number the OrderID when an item is deleted so that it moves all the items below it in the same CatalogID group up one value to still reflect the correct order and not skip OrderID values. Hello phpfreaks I'm a bit new to PHP, as well as this forum. I'm learning in a fast way, but there's something I can't seem to figure out, nor find it on google. I'm sure it's a simple and basic trick, but like I said, I'm just a beginner So the question is: How can I store multiple words to an array, using only 1 input form field? I guess it's with a for-loop..? So everytime you hit the 'submit' button, a new word should be added to the array. My problem is that I'm always overwriting ONE word.. This is what I've got so far.. : Code: [Select] <?php if (isset($_POST['word'])){ $word = $_POST['word']; $word = strip_tags($word); $word = trim($word); $word = htmlentities($word); } else { $word = ""; } ?> <div id="arrays"> <p>Add a word to the array below:<br /><br /></p> <form action="index.php" method="post"> <input id="word" name="word" type="text" value="<?php echo $word; ?>" /> <br /><input class="btn" type="submit" value="Submit" /> </form> <br /> <p> <?php $array = array("apple", "banana", "lemon", $word); for ($i = 0; $i < count($array); $i++){ echo $array[$i] . " "; } ?> </p> </div> Also: I'm using PHP 5, in combination with xHTML strict 1.0. I'm dealing with data that WordPress creates for Users when they register and subscribe, and to use it for other purposes, I have to wrap my head around serialized data. It's not sinking in well. The below code works well for what I wanted at the time. It takes into consideration where the Subscriber lives (divided up into five areas) and counts how many I have. That is noted by wp_s2member_custom_fields and ANY s2member_level. There are three levels, and I need to actually note how many there are at each Member level. There is another line of data for each user_id meta_key = wp_capabilities meta_value = a:1:{s:15:"s2member_level2";s:1:"1";} Code: [Select] $custom = 'SELECT * FROM wp_usermeta WHERE meta_key = "wp_s2member_custom_fields" AND user_id IN (SELECT user_id FROM wp_usermeta WHERE meta_value LIKE "%s2member_level%")'; $c_results = mysql_query($custom); $region = array(); while($line = mysql_fetch_assoc($c_results)) { $meta_value = unserialize($line['meta_value']); $region[$meta_value['county']]++; }; foreach ($region as $key => $value) { echo "Region $key: $value members<br>"; } Hi I am new to PHP / mySQL although not to programming and am trying to work out how to deal with the following situation: I have a form for a user to add a book to a database, along with the genres that the book belongs to. Each book can have a number of genres . There are 3 tables, books, genres and bg_xref in the following formats table: books fields: id, title, author, date published table: genres fields: id, genre table: bg_xref fields: id, book_id, genre_id I am now trying to build the form that allows the user to update an existing entry for a book. the genres are selectable from a multi-selection list which I am populating from all the possible values in the genres table. Currently I have the following database selections: mysql_select_db($database_conn, $conn1); $query_rs_getBooks = "SELECT books.id, books.title, books.author, bg_xref.genre_id FROM books LEFT JOIN bg_xref ON books.id = bg_xref.book_id"; $rs_getBooks = mysql_query($query_rs_getBooks, $conn1) or die(mysql_error()); $row_rs_getBooks = mysql_fetch_assoc($rs_getBooks); mysql_select_db($database_conn, $conn1); $query_rs_getGenre = "SELECT * FROM book_genres ORDER BY genre ASC"; $rs_getGenre = mysql_query($query_rs_getGenre, $conn1) or die(mysql_error()); $row_rs_getGenre = mysql_fetch_assoc($rs_getGenre); I have then created a form that the user uses to update the book, but am trying to work out how to prepopulate the selection list based on teh results of the join e.g. <form method="POST" action="<?php echo $editFormAction; ?>" name="update_book"> <fieldset class="full"> <legend>Enter book details below</legend> <table> <tr><td>Title: </td><td><input type="text" size="50" value="<?php echo htmlentities($row_rs_getBooks['title'], ENT_COMPAT, 'iso-8859-1'); ?>" name="title"></td></tr> <tr><td>Author: </td><td><input type="text" size="30" value="<?php echo htmlentities($row_rs_getBooks['author'], ENT_COMPAT, 'iso-8859-1'); ?>" name="author_surname"></td></tr> <tr><td>Genre(s)</td><td><select name="genre" multiple size="4"> <?php do { ?> <?php if (($row_rs_getBooks['genre_id']) != $row_rs_getGenre['id']) { ?> <option value="<?php echo $row_rs_getGenre['id']?>"><?php echo $row_rs_getGenre['description']?></option> <?php } else { ?> <option value="<?php echo $row_rs_getGenre['id']?>" selected><?php echo $row_rs_getGenre['description']?></option> <?php } } while ($row_rs_getGenre = mysql_fetch_assoc($rs_getGenre)); $rows = mysql_num_rows($rs_getGenre); if($rows > 0) { mysql_data_seek($rs_getGenre, 0); $row_rs_getGenre = mysql_fetch_assoc($rs_getGenre); } ?> </select></td></tr> </table> </fieldset> <input type="hidden" name="id" value="<?php echo $row_rs_getBooks['id']; ?>"> <input type="submit" value="Update book details"> <input type="hidden" name="MM_update" value="update_book"> </form> Book id = 1 is classified against genres 1 and 5, so my SQL query returns 2 rows: book.id = 1 + bg_xref.genre_id = 1 book.id = 1 + bg_xref.genre_id = 5 At the moment the form is generated for the first row of the results set with <tr><td>Genre(s)</td><td><select name="genre" multiple size="4"> <option value="5">Humour</option> <option value="4">Non Fiction</option> <option value="2">Novel</option> <option value="3">Picture Books</option> <option value="1" selected>Poetry</option> with a second entry in the results set for book 1 and genre 5. What I need to end up with is a second occurence of book 1 with both genres 1 and 5 set in the form. Thanks Stuart Before I get into my problem a couple of things. First, this is a work project. My organization cannot afford a full time developer so as a database guy I'm being asked to develop a web based data system using php/html/mysql/javacript/etc. So I am not asking anyone to help me cheat or violate an honor code for a school project. Also I am having to learn PHP on the fly, by the seat of my pants. Second, my organization is using a version of PHP older that 5.5.X and I am powerless to update the version. So I know that some of the syntax I am using has been deprecated in more recent PHP versions. I don't mean to sound snarky or ungrateful but I really need some help solving this problem versus unhelpful comments about deprecated code. Third I am adapting code from the guys at TechStream so H/T to them. Here is what I am trying to build. My office helps other offices in my large organization manage their records through the creation of a file plan. We are currently using a clunky, user-unfriendly Access database that was created back in 2009. I am tasked to transition that Access hoopty into a proper, web-based, user friendly system. The index.php form page consists of 2 parts. You can see the original TechStream demo he http://demo.techstre...ssing-with-PHP/ I've adapted the top part of the form ("Travel Information") for my users to enter information about their office such as Office Name, Office Code, Office Chief, Creator (the user), Status and date. I've adapted the bottom part of the form ("Passenger Details") to be "Folder Details". This is an html table where users can add up to 10000 rows to list all the folders for their office by entering the folder name in the text box and then assign descriptors to each folder using the drop down menus. I've changed the drop down menus to reflect the descriptors we need, i.e. file-series, classification, media type. The user needs the flexibility to add folders as the number of folders will vary between offices. This adding and deleting of folders is accomplished dynamically through a javascript script.js file. Now, here's my problem. When the user clicks submit button that fires a php script that runs an insert into query to place the array data into the backend mysql database. However, when the foreach loop is only inserting the office office from the top portion of the form with the first folder in the bottom portion of the form. In other words let's say the user fills out the top part with his office information and then adds 5 folders into the html table at the botton. The first folder will be inserted into the database table with both office information and folder information. However the subsequent 4 folders will have their folder information inserted into the table but the office information fields will be null. The office information needs to be inserted with each folder the user adds to the html table piece. I suspect that my foreach loop is only capturing that office information on the first iteration of the loop and then flushing or deleting the office information after the first loop. Also, I suspect there is some disconnect between the html table for entering individual folders and the top part of the form that is not in html format. Any help I can get is most welcome. Thanks in advance! Code is below. index.php <?php session_start(); if(!isset($_SESSION['myusername'])) { header('Location:index.php'); } echo $_SESSION['myusername']; echo '<a href="logout.php"><span>Logout</span></a></li>'; <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Records Management File Plan Application</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <link rel="stylesheet" type="text/css" href="css/default.css"/> <script type="text/javascript" src="js/script.js"></script> </head> <body> <form action="InsertFileDetailArraytoDB.php" class="register" method="POST"> <h1>Office File Plan Application/h1> <fieldset class="row1"> <legend>Office Information</legend> <p> <label>Office Code * </label> <input name="officecode[]" type="text" required="required"/> <label>Date* </label> <select class="date" name="day[]"> <option value="1">01 </option> <option value="2">02 </option> <option value="3">03 </option> <option value="4">04 </option> <option value="5">05 </option> <option value="6">06 </option> <option value="7">07 </option> <option value="8">08 </option> <option value="9">09 </option> <option value="10">10 </option> <option value="11">11 </option> <option value="12">12 </option> <option value="13">13 </option> <option value="14">14 </option> <option value="15">15 </option> <option value="16">16 </option> <option value="17">17 </option> <option value="18">18 </option> <option value="19">19 </option> <option value="20">20 </option> <option value="21">21 </option> <option value="22">22 </option> <option value="23">23 </option> <option value="24">24 </option> <option value="25">25 </option> <option value="26">26 </option> <option value="27">27 </option> <option value="28">28 </option> <option value="29">29 </option> <option value="30">30 </option> <option value="31">31 </option> </select> <select name="month[]"> <option value="1">January </option> <option value="2">February </option> <option value="3">March </option> <option value="4">April </option> <option value="5">May </option> <option value="6">June </option> <option value="7">July </option> <option value="8">August </option> <option value="9">September </option> <option value="10">October </option> <option value="11">November </option> <option value="12">December </option> </select> <select name="year[]"> <option value="2013">2013 </option> <option value="2014">2014 </option> <option value="2015">2015 </option> <option value="2016">2016 </option> </select> </p> <p> <label>Office Chief* </label> <input name="officechief[]" required="required" type="text"/> <label>Status* </label> <select name="status[]"> <option value="Draft">Draft </option> <option value="Submitted">Submitted </option> <option value="Approved">Approved </option> </select> </p> <p> <label>Creator * </label> <input name="creator[]" required="required" type="text"/> </p> <div class="clear"></div> </fieldset> <fieldset class="row2"> <legend>Folder Details</legend> <p> <input type="button" value="Add Folder" onClick="addRow('dataTable')" /> <input type="button" value="Remove Folder" onClick="deleteRow('dataTable')" /> <p>(All actions apply only to entries with check marked check boxes.)</p> </p> <table id="dataTable" class="form" border="1"> <tbody> <tr> <p> <td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td> <td> <label>Folder Name</label> <input type="text" required="required" name="BX_NAME[]"> </td> <td> <label for="BX_fileseries">File Series</label> <select id="BX_fileseries required="required" name="BX_fileseries[]"> <option>100-01-Inspection and Survey/PII-NO</option> <option>200-02-Credit Card Purchases/PII-NO</option> <option>300-07-Time and Attendance/PII-YES</option> </td> <td> <label for="BX_classification">Classification</label> <select id="BX_classification" name="BX_classification" required="required"> <option>Unclassified</option> <option>Confidential</option> <option>Secret</option> <option>Top Secret</option> <option>Ridiculous Top Secret</option> <option>Ludicrous Top Secret</option> </select> </td> <td> <label for="BX_media">Media</label> <select id="BX_media" name="BX_media" required="required"> <option>Paper</option> <option>Shared Drive</option> <option>Film</option> <option>Floppy Disk</option> <option>Mixed</option> <option>Other</option> </select> </td> </p> </tr> </tbody> </table> <div class="clear"></div> </fieldset> <input class="submit" type="submit" value="File Plan Complete »" /> <div class="clear"></div> </form> </body> </html>PHP script with foreach loop to loop through the array from index.php and insert into database: InsertFileDetailArrayToDB.php /* When the user has finished entering their folders, reviewed the form inputs for accuracy and clicks the submit button, this will loop through all folder entries and using the SQL insert into query will place them in the database. When it completes data insertion it will redirect the user back to the file detail input form*/ <?php /*this part requires the user to be logged in and allows their user name to be included in the insert into query. If you remove the "ob_start();" piece it will screw up the header statement down at the botton. See the comments by the header statement for an explanation of its purpose*/ ob_start(); session_start(); if(!isset($_SESSION['myusername'])) { header('Location:index.php') } /*these two lines would ordinarily display the user name and a link a allowing the user to log out. However this php script does not output anything so the user will never it.*/ echo $_SESSION['myusername']; echo '<a href="logout.php"><span>Logout</span></a></li>'; ?> <?php /*this include statement connects this script to the MySQL database so the user form inputs can be inserted into the file_plan_details table*/ include ('database_connection.php'); foreach($_POST['BX_NAME'] as $row=>$BX_NAME) { $BX_NAME1 = mysql_real_escape_string($_POST['BX_NAME'); $officecode1 = mysql_real_escape_string($_POST['officecode'][$row]); $username1 = mysql_real_escape_string($_SESSION['myusername'][$row]); $day1 = mysql_real_escape_string($_POST['day'][$row]); $month1 = mysql_real_escape_string($_POST['month'][$row]); $year1 = mysql_real_escape_string($_POST['year'][$row]); $creator1 = mysql_real_escape_string($_POST['creator'][$row]); $officechief1 = mysql_real_escape_string($_POST['officechief'][$row]); $status1 = mysql_real_escape_string($_POST['status'][$row]); $BX_fileseries1 = mysql_real_escape_string($_POST['BX_fileseries'][$row]); $BX_classification1 = mysql_real_escape_string($_POST['BX_classification'][$row]); $BX_media1 = mysql_real_escape_string($_POST['BX_media'][$row]); $fileplandetailinsert1 = "INSERT INTO file_plan_details (folder_name, office_code, user_name, day, month, year, creator, office_chief, status, file_series, classification, media) VALUES ('$BX_NAME1','$officecode1','$username1','$day1','$month1','$year1','$creator1','$officechief1','$status1','$BX_fileseries1','$BX_classification1','$BX_media1')"; mysql_query($fileplandetailinsert1); } /*this header statement redirects the user back to the folder detail input form after it inserts data into the db After I build a main navigation page, I will switch out index.php with whatever I name the script that will produce the main navigation page*/ header('Location:index.php'); ?>script.js function addRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; if(rowCount < 10000){ // limit the user from creating fields more than your limits var row = table.insertRow(rowCount); var colCount = table.rows[0].cells.length; for(var i=0; i<colCount; i++) { var newcell = row.insertCell(i); newcell.innerHTML = table.rows[0].cells[i].innerHTML; } }else{ alert("Maximum Passenger per ticket is 5."); } } function deleteRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; for(var i=0; i<rowCount; i++) { var row = table.rows[i]; var chkbox = row.cells[0].childNodes[0]; if(null != chkbox && true == chkbox.checked) { if(rowCount <= 1) { // limit the user from removing all the fields alert("Cannot Remove all the Passenger."); break; } table.deleteRow(i); rowCount--; i--; } } } Edited by mac_gyver, 17 December 2014 - 01:13 PM. code tags around posted code please Hi, This is the code I made to show the problem: $useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 ( .NET CLR 3.5.30729)"; $timeout = 10 ; $cookie = tempnam ("/tmp", "CURLCOOKIE"); $post = array('_method'=>"put", 'authenticity_token'=>' zcvcxfsdfvxcv', 'profile_image[a]'=>"@Girl-Next-Door-movie-f01.jpg" ); $ch = curl_init(); curl_setopt( $ch, CURLOPT_USERAGENT, $useragent); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); curl_setopt($ch, CURLOPT_URL, "http://localhost/test.php"); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie ); curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true ); curl_setopt( $ch, CURLOPT_ENCODING, "" ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch, CURLOPT_AUTOREFERER, true ); curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); # required for https urls curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout ); curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout ); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); $html = curl_exec($ch); curl_close($ch); Now this link used above: http://localhost/test.php has this code: print_r($_POST); print_r($_FILES); It simply prints whats in post and files. So the above code displays this on screen: Code: [Select] Array ( [_method] => put [authenticity_token] => zcvcxfsdfvxcv ) Array ( [profile_image] => Array ( [name] => Array ( [a] => Girl-Next-Door-movie-f01.jpg ) [type] => Array ( [a] => image/jpeg ) [tmp_name] => Array ( [a] => /tmp/phppLJPQV ) [error] => Array ( [a] => 0 ) [size] => Array ( [a] => 55377 ) ) ) but we need to modify the code so that it should display this: Code: [Select] Array ( [_method] => put [authenticity_token] => zcvcxfsdfvxcv ) Array ( [profile_image[a]] => Array ( [name] => Girl-Next-Door-movie-f01.jpg [type] => image/jpeg [tmp_name] => /tmp/phppLJPQV [error] => 0 [size] => 55377 ) ) Meaning, it is taking this(profile_image[a]) as an array when we are defining $post because that's how curl recognizes that we want to upload only a file or an array of files on server by http post. So, basically the problem is the name of the input field that is defined as an array (profile_image[a]) on the web page that we are trying to mock. If this(profile_image[a]) was this (profile_image_a)(without []) on that webpage, then it would not have been a problem. So, if you understand, this is basically a syntax problem. I do not know how stop curl from reading 'profile_image[a]' as an array here 'profile_image[a]'=>"@Girl-Next-Door-movie-f01.jpg. I need curl to read 'profile_image[a]' as an string and not array. I have to use [], otherwise I will not be able to mock the webpage as the name will change. It will give error. I hope I explained the problem and also gave you a way to test if you have a solution. Again, if your code starts displaying this: Code: [Select] Array ( [_method] => put [authenticity_token] => zcvcxfsdfvxcv ) Array ( [profile_image[a]] => Array ( [name] => Girl-Next-Door-movie-f01.jpg [type] => image/jpeg [tmp_name] => /tmp/phppLJPQV [error] => 0 [size] => 55377 ) ) ,then we have a solution. Thanks for helping in advance. Regards, Manoj MySQL returns an error in the form of a number, a state, and a message. Without parsing the message you will not be able to determine what column is duplicated.While parsing the error code, I have also notice that, if you have multiple unique fields as duplicates, only the first duplicate encountered will be returned in the message. This is not very helpful to the end user.
Is there any way to parse the returned error code to reflect all duplicate fields, please see sample code below?
$error=array(); $sql = 'INSERT INTO staff(username, email, phone) VALUES (?, ?, ?)'; $stmt = $conn->stmt_init(); $stmt = $conn->prepare($sql); // bind parameters and insert the details into the database $stmt->bind_param('sss', $username, $email, $phone); $stmt->execute(); if ($stmt->errno == 1062) { $errors[] = "One of the fields is already in use."; } Man, I'm having a rough week with questions--if you're following at home. Basically matching a Coach's first and last name to another table, which if matched will yield information about that coach's team. Code: [Select] // or get user by username $current_user = wp_get_current_user(); $current_first = $current_user->user_firstname; $current_last = $current_user->user_lastname; $current_id = $current_user->ID; echo '<div class="contact_form">'; echo $current_first . ' ' . $current_last .' :: '; $query = "SELECT * FROM schools WHERE coachFirst='".$current_first."' AND coachLast='".$current_last."'"; $result = mysql_query ($query); if(!$result) { echo 'There is not a match for your name.'; } else { while($school= mysql_fetch_array($result)) { echo $school['school'] . ' ' . $school['id']; include(ABSPATH ."wp-content/plugins/my-team/form.php"); } echo '</div>'; echo '<div class="roster">'; include(ABSPATH ."wp-content/plugins/my-team/roster.php"); echo '</div>'; } I hope I can explain what is happening. I have created two forms in PHP. The first 'almost' works, i.e. it shows the data. But I have two problems - 1) the second pulldown menu is always empty and 2) $value from the first pulldown menu ALWAYS equals the last entry thus the last 'if' in the function subdomains ($domains) is always called (but still empty). The code may explain this better than me:
<!DOCTYPE html> <html> <body> <!-- processDomains.php is this file - it calls itself (for testing purposes so I can see what is happening) --> <form action="processDomains.php" method="post"> <?php // create the domains array (there are actually several entries in the array but I cut it down for testing) $domains = array (1 => 'Decommission', 'Migration'); echo "Select Domain:"; echo "<br>"; // Make the domain pull-down menu - this displays correctly echo '<select name="domain">'; foreach ($domains as $key => $value) { echo "<option value=\"$key\">$value</option>\n"; } echo '</select>'; // input doesn't matter what is 'submitted', always goes to last $value echo '<input type="submit" name="submit" value="Submit">'; // call function subdomains subdomains ($value); function subdomains ($domains) { // define values for each array - each array contains available choices for the subdomain pulldown menu $migration = array (1 => 'Application Migration', 'Application Patch', 'Application Upgrade'); $decommission = array (1 => 'Applications', 'Servers', 'Storage'); if ($domains === 'Migration') { echo "Select subdomain:"; echo "<br>"; // Make the Migration pull-down menu echo '<select name="migration">'; foreach ($migration as $key => $value) { echo "<option value=\"$key\">$value</option>\n"; } echo '</select>'; } else if ($domains === 'Decommission') { /* === * since 'Decommission' is the last entry in the 'Domains' pulldown list, $value ALWAYS equals * 'Decommission' and $domains equals $value. So this menu SHOULD work but is always * empty. Thus, two problems - the pulldown menu is always empty and $value isn't based * upon user input. */ echo "Select subdomain:"; // this prints so I know I'm in 'Decommission (I eliminated the echo "$domain" to show I'm always coming here)' echo "<br>"; // Make the 'Decommission' pull-down menu echo '<select name="decommission">'; foreach ($decommission as $key => $value) { echo "<option value=\"$key\">$value</option>\n"; } echo '</select>'; echo '<input type="submit" name="submit" value="Submit">' ) // end of 'if-else' } // end of function 'subdomain' ?> </form> </body> </html>Let me say thank you in advance and I appreciate the help! I know I'm doing something (or more than one thing) wrong and I hope someone can tell me what it is. Best Regards! Edited by mac_gyver, 19 January 2015 - 09:37 PM. code tags around posted code please |