-
Posts
5,536 -
Joined
-
Days Won
192
Everything posted by mac_gyver
-
Form data to CSV using PHP (code problems)
mac_gyver replied to NickWrenLab's topic in PHP Coding Help
i'm not sure why people keep writing-out/copy/paste/over-type line after line after line after line of repetitive code, for hours on end, that only differs in the the variables/names between lines of code in a section. programming is already a tedious task. creating all this repeating logic, unless you are using it to learn touch-typing, isn't an effective use of time and isn't using the computer as a tool to get a job done. dynamically get the computer to do this for you, by operating on the data as a SET by using php's array functions. define all the form fields in an array, with the form field name, label, the field type, choices for check boxes and radio buttons, validation rules, ... that would let you simply loop over the definition to produce the form and process the form data. an example of trimming all the form data at once, by treating it as a SET of data - $data = array_map('trim',$_POST); // get a copy of the trimmed data - and if you are submitting arrays of data, just make a call-back function and use array_walk_recursive() instead. this one line eliminates all those 20-40 sets of logic and eliminates all the typo's and checking to make sure you have logic for each input. just reference $data['form_field_name_here'] to use the trimmed data. dynamically reference any existing form data when you are looping over the defining array to displaying the form. dynamically reference any error array elements the same way. doing this also has the advantage of implement DRY (Don't Repeat Yourself) programming, because any particular code/markup will only exist once, so if you need to fix or change what it does, you only have to make the change in one place. once you have implemented this for one form, you now have a form-generator/processor that you can use to implement any form, simply by changed the defining array and changing any code that uses the submitted form data. you would even use the defining array to dynamically produce an INSERT query for a database design, the fputcsv() statements for a file based design, or build the message body for an email based design, all without writing out code for every value that's being operated on. -
the undefined index errors are because your form processing code is running unconditionally, before there is any form data to process. your form processing code should be at the top of your file, before the <!DOCTYPE html> tag (so that any validation errors can be displayed when you redisplay the form) AND the form processing code needs to be inside of a conditional statement that's testing that a form has been submitted, so that the form processing code only runs when there is form data. edit: see the following post for a suggested code layout that will help make your code fool proof - http://forums.phpfreaks.com/topic/297824-database-issues-and-working/?do=findComment&comment=1519095
-
@benanamen, the problem isn't strict mode. it's because you don't put single-quotes around the place-holders in the sql syntax.
-
it would seem that you have removed the code you previously had that was setting the PDO error mode to exceptions. the false value being returned means that the execute statement failed and an exception wasn't thrown for the error. so, why did you remove (or not copy) the error setting you did have in your code?
-
this is why you should use the documentation to learn the basics. if you read the relevant sections of the php.net documentation for the PDO class, you will find the meaning of and see examples showing how to use each method. while slightly off topic, a person's age is not a fixed number, unless they are dead. you should be storing a person's date of birth, and calculating their age.
-
the capitalization of your column name in the database table probably isn't exactly - repair_id. The query won't produce an error if the capitalization in the query doesn't match the actual table definition, but the php code won't match the column name. if your php error_reporting/display_errors settings are actually turned full on, you would be getting an undefined index error message, unless this code is inside of a html tag or a form element, in which case the error message will only be seen if you do a 'view source' of the output in your browser.
-
are you sure there's data in that column in the database table? without an ORDER BY term in your query, that query is will return the first row that's stored in your table, which is not even guaranteed to be the first row you inserted, and which can even change if you optimize or backup/restore your data. i suggest you review all the posts in your last thread, so that you won't be writing and testing extra code trying to get and use data that you cannot guarantee the value of until after a row has been inserted into your database table.
-
Display All Records With The Same Stockin_id
mac_gyver replied to dardime's topic in Third Party Scripts
the reason you are getting the wrong output is because you are trying to use the database methods in the pagination class to run your own data retrieval queries, inside of a loop, separately from the pagination query. the pagination class shouldn't be extending the db class, it should be dependent on the db class, so that you don't find yourself calling page methods that don't have anything to do with pagination. you also wouldn't be calling your own data retrieval queries, since that would bypass what the pagination is trying to accomplish. for pagination to work, you would build one query that gets the data you want in the order that you want it. the pagination methods would just query for and retrieve the correct logical page of data based on the page number that has been requested. to do what you are attempting using this code, you would build your one main query so that it gets the data you want and orders the rows by the stockin_id, so that rows having the same stockin_id value will be together in the result set. -
there are at least three problems with your code - 1) if you are doing this for real, you would not delete any data. you would keep the data for reference. 2) you would not create a database connection, run the code within one function, and close the database connection. in fact, your code is including/requiring the same files multiple times and creating database connections in a ton of places. 3) you apparently missed post #7 in this thread. you CANNOT get the highest value from a database table, add one to it, and USE that value. you will end up with concurrent instances of your code using the same value.
-
you cannot get the current value of either an auto-increment or your own maintained column value, add one to it and use that value. you will end up with concurrent instances of your code that will use the same value. if you want to do this and have the displayed value be the one that gets used in the database, you will need to pre-insert a row, using an auto-increment field, get that row's id, then display that id and use it to UPDATE the row when the form is actually submitted. this will have an affect of empty rows/wasted ids if anyone doesn't complete the form. the correct method would be to NOT try to display this information in the form. after the form gets submitted and the data is inserted, you would then have the actual id that you can display/email to serve as a confirmation number.
-
the way to do inventory, is like a checking account or an credit-card account register. you store a row for each + or - transaction. the table tracking the inventory would hold the book_id (you would also have a 'book' table that holds the unique information about each book/title), user_id (who added or subtracted a quantity), the date-time (when the user added or subtracted a quantity), the quantity, and a memo/comment/status column. you would initially store a row for each book/title, with the a positive quantity of how many are on hand. the user_id for that row would be the admin/librarian that initially enters the information. if more books are ordered and added to the inventory, you would add a row with a positive quantity. when someone checks out a book(s), you would enter a row for each different book_id, with the quantity as a negative value. when they check in a book(s), you would enter a row for each different book_id, with the quantity as a positive value. to get the quantity on hand, you would use a query with SELECT SUM(quantity) .... .... GROUP BY book_id. if you are giving each book a unique id/serial number, you would still do the inventory this way, but you would have a separate row for each separate book, with a serial_number column to record exactly which book was checked out/in. the quantity column would then either be a 1 or a -1.
-
you can display the next probable id, but your code or the visitor cannot use this value, because if more than one instance of your form/page is being displayed at the same time, the value being shown will be same on all the instances of the form/page, but the actual value that gets inserted by the database will be different. so, the question is, why do you want to do this as it will just confuse the visitor with a piece of information that he doesn't need to know at the time the form is being displayed, if at all?
-
you are passing a string and an array containing a quantity into your function. that doesn't make any sense from a definition standpoint. these should just be two values. there's no point in the quantity being an element in an array. wouldn't you just pass in the book-name/book-id and a quantity? next, why are you storing the quantity in each row? if you are making a row for each book (30 rows for your stated example, 12 rows for your apparent test data), storing the quantity in each row isn't relevant. what data do you want to store in each row? finally, for what purpose are you doing this? if this if for an inventory system, you would want a single row holding the quantity, not a separate row for each copy of a book.
-
the browser should just be displaying the current state. the control over what happens should be by the server-side code, regardless of how many times the current state is requested/displayed. what exactly is occurring when a page gets requested/refreshed that is causing a problem? are you using post method forms to submit data, with one-use-tokens to prevent double-submission, followed by a header() redirect to the exact same url that the form submitted to, to cause a get request to display the current state?
-
the total quantity is a derived value. you should not maintain a value for it, but calculate it when needed. your cart appears to be storing the quantity of each item as the value for each array entry (and if it's not, that is how you should be storing the quantity for each item.) you can just use array_sum($_SESSION['cart']) to get a total count of things in the cart. using count($_SESSION['cart']) would tell you how many different items are in the cart. your class method doesn't use/need an input parameter. why are you defining and calling it with one?
-
based on what i learned about the code, i finally figured out what the OP is referring to in this thread. this is the reason why you need to write applications without it taking a wall of repetitive code and why you need to put comments in your code to document what it is doing, so that anyone looking at the code can figure it out. the select/option menu in question is letting the visitor select among the different costs, with the value='....' attribute being the actual cost. the missing $chosencost_1 variable is actually present, after the registration form has been submitted, because the form code is being included back into the Check_Registration_Form11.php page, which is where the $chosencost_1 variable is at. the reason you are likely getting a 1 for a cost value, is because whoever/a-bot-script that is submitting the form, has figured out that you are using the submitted cost, so they are trying to get a $1 bargain on a course. this code is completely flawed in how it is operating. the most direct fix would be to do the following - 1) only the course id, the value in $recid on the Course_Details page, should be submitted between steps (your course registration data structure should actually only store the course id, student id (the unique information about a student should be stored in a user/student table, not in the course registration table), and any unique information about each registration, but i doubt you are going to change your data to do it this way.) 2) any page that needs to use or display the course data should use the submitted $recid value (after validating it) to query for the course information on that page. 3) any cost section should use a type value that identifies a choice among the available different costs, not the actual cost value. the actual cost the code uses should take the submitted type and get the actual cost from wherever it is stored. you should also validate that the type that was submitted is available/valid for the user, using whatever rules you have. which begs the question - why is the user even picking what price he gets? shouldn't that be an administrative choice, not a user accessible choice? 4) you should pass a minimum of information between pages in the form and any information you do pass through a form must be validated at each step. you may want to consider using a session variable to hold an array of the validated data so that you don't need to re-validate the data at each step.
-
@benanamen, it's against the forum rules to solicit work, except in the freelancing/services-offered forum section.
-
went through the code trying to figure out the program flow. here's some notes - Course_Details11.php - this page receives an id as an input, uses that id to retrieve and display the information for the course the id corresponds to. if the visitor chooses to register for the course, about 40 pieces of course information are passed to the next page as get parameters in the form's action='....' attribute. the only post data is the submit button. Registration_Form11.php - this page copies/validates/casts the data from the course_details page (18-19 items out of the 40 that are put into the url), puts this data (~11 items) into hidden form fields (without any html encoding, which may be why some form values don't work, if the values/upstream-values contain any quotes, breaking the html syntax), displays the user form fields, with any validation errors (see the check_registration_form notes next), and submits to the Check_Registration_Form11.php page. Check_Registration_Form11.php - this page copies/validates/casts ALL (hopefully, didn't bother to count the hard-coded line after line of code) the data from the registration form page. if there are validation errors, it includes the registration form page (which is a complete html document itself, giving two nested documents at this point) so that the form and any errors can be displayed. since there is no specific form processing conditional statement in any of this code, doing the include, causes all form processing/form display logic in the registration page to run again. if there are no validation errors, some/all of the data is saved in a 'Online_Activity' database/table, but this isn't used by the code to save on passing data to the next step. the user data is displayed as a conformation check and ALL the $_POST data (this time with html encoding, though not with all quote types encoded, which is amazing because the display section is using html encoding with all quote types encoded) is put into hidden form fields for the next page. to correct any data, you must use the browser's back button. this page submits to the process registration page. Process_Registration11.php - this page validates JUST the original course_details data (19 items). it doesn't validate the user entered data. it finally saves the data to a 'Web Registration Information' database/table. then sends some emails, and updates some more database information. @ the OP, if this is something that is actually being used for registration at a school, and it is beyond your abilities to find and fix the problem among the wall of 6800+ lines of uncommented code, you should expect to hire someone to fix this for you, rather than to get free programming services on a programming help forum.
-
the most likely reason for the random failures of the code is probably due to different browsers handling markup errors differently. the html in the pages being produced needs to be valid to have a chance at working the same in all browsers/browser-versions. what a mess. this code is long over due to be written from scratch, using general, data driven, DRY, programming. there's a ton of hard-coding (i even saw a 2015 year being used in a path that would need to be manually changed each new year, and i'm guessing this is what the 11 in the file names are there for, to distinguish different hard-coded instances of the site) and repetition of form/form-processing code between main and included files. of the 6800+ lines present in the .zip, there's probably only about 2000 lines needed to do this task.
-
see the following example code that shows several of these suggestions - <?php include "dbinfo.php"; // do this once, since both your form and form processing code needs a db connection // the defined constants DB_NAME, DB_USER, DB_PASS, and DB_HOST would be defined in your dbinfo.php file $pdo = new pdo("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=utf8",DB_USER,DB_PASS); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false); // form processing code - if(isset($_POST['update'])) { echo '<pre>',print_r($_POST,true),'</pre>'; // examine what the submitted form data is // i'll leave it up to you to work on the form processing code } // members table - id, member (i'm going to assume this is a something like a username or should it be the member's/user's firstname/lastname) // divisions table - id, name, image // member_div table - member_id, division_id $id=$_GET['id']; // the member to show the data for // one JOIN'ed query that gets the data you want in the order that you want it $query = " SELECT d.id div_id, d.name div_name, d.image div_image, m.username, m.id user_id, md.member_id IS NOT NULL AS checked FROM divisions d JOIN members m LEFT JOIN member_div md ON d.id = md.division_id AND m.id = md.member_id WHERE m.id = ? ORDER BY div_name "; $stmt = $pdo->prepare($query); // prepare the query $stmt->bindvalue(1,$id); // bind the input data to the place-holder $stmt->execute(); // run the query $result = $stmt->fetchall(); // fetch all the rows. this will be an empty array if the query didn't match any row(s) // produce the output from the $result array of data from the database query if(empty($result)){ echo 'There is no data to display'; // this won't occur unless there is no divisions and members data. } else { // there is data to display $record = $result[0]; // make a copy of the first row for the heading information ?> <h3>Updating divisions for member: <?php echo $record['username'];?></h3> user's id: <?php echo $record['user_id'];?> <br> <form method="post" > <table width="60%" border="1" align="left"> <th width="5%">id</th><th width="45%">division</th><th width="45%">image</th><th width="5%">status</th> <?php foreach($result as $row) { echo "<tr><td>{$row['div_id']}</td>"; echo "<td>{$row['div_name']}</td>"; echo "<td>{$row['div_image']}</td>"; $chk = $row['checked'] ? 'checked' : ''; // produce the checked state for each checkbox echo "<td><input type='checkbox' name='chk[{$row['div_id']}]' $chk /></td>"; echo "</tr>\n"; } ?> </table> <input name="update" type="submit" value="Update"> </form> <?php } ?> note: the db column names in this example may not match your's and would need to be modified to run at all.
-
checked check-boxes will be set in the submitted form data. unchecked check-boxes won't be present in the submitted form data. therefore, the value isn't really important and can be left out of the code. it's easy to detect what check-boxes are checked, but you must also be able to remove the stored data for check-boxes that go from checked to not checked. the easiest way to do this is to just remove all the relevant data and then set/insert the data for the checked check-boxes. your code also isn't using the id='....' attribute, so don't produce that in your code unless you need it. your checkbox name='....' attribute should be an array name with the array key/index being the division id value. this will give you a php array from the submitted form data with the division id values that were checked. the line in your code would look like - echo '<td><input type="checkbox" name="chkbox['.$record2['id'].']" /></td>'; your members table should just hold the unique information about each member. it should not hold this division data. you actually need a 3rd table to hold this data, with one row for each piece of data, with member_id, and division_id columns. the member_id and division_id columns need to be set up with a unique composite index to enforce unique data pairs. to retrieve the data to display it, you should use one JOINed query, then just loop over the data and output it the way you want. now the bad news - the mysql_ database library of functions are obsolete and will be removed from php in the near future. you need to learn and use either the PDO (the best choice) or the mysqli_ library of functions so that you are learning current technology. you also need to properly treat external data being put into sql query statements. the best way of doing this is to use prepared queries, with place-holders/bound data in the sql statement for the data values. both the PDO and mysqli_ libraries support prepared queries, but PDO is easier and more consistent to use. P.S. $_PHP_SELF is also obsolete (and i'm pretty sure that's got an extra _ in it) and should not be used. for html5, you can just leave the action='...' attribute out of the <form....> tag or you can use action='#'
-
if your server is set up correctly, and if it's not, you can fix to be so, $_SERVER['DOCUMENT_ROOT'] refers to the document root folder and can be used for building an absolute file system path for include/require statements.
-
@sigmahokies, the php programming help forum section is for asking for help with code you have written. it is not for asking how you can learn something or for links to sites, because we don't know the complete requirements for what you are looking for. this is not a suggestion for you to try and list all the requirements that you are looking for. it's a suggestion that it's up to you to do the research for the information that you want to know, not to ask others to do this for you, because you are the only one here that knows what exactly you are looking for and at what level of detail that matches your programming knowledge and experience. if you have specific questions about how you would design something, you can post them in the Application Design forum section, but please read the rules/stick-posts for that forum section, it is not to get someone to completely do your design for you, just to answer specific questions you have while you are doing the design - see the sticky/pinned post http://forums.phpfre...ication-design/
-
i recommend using a 'template' method, where the first instance of your form field(s) is(are) inside of a <div></div> container and become a source template that you use when appending the dynamically added form fields. this eliminates the need to duplicate the markup for the form fields in both the html and in the javascript, i.e. DRY (Don't Repeat Yourself) programming. next, you need to use an array name for your form fields. this eliminates the need to maintain a counter in the javascript code and allows you to use php's array functions to loop over the submitted data. see the following example - <script type="text/javascript"> function addField() { // create an empty div element var div1 = document.createElement('div'); // get the template html and put it into the empty div div1.innerHTML = document.getElementById('template').innerHTML + "<input type='button' onClick='removeField(this)' value='-'>"; // append the new div to the target area on the page document.getElementById('add_here').appendChild(div1); } function removeField(div){ document.getElementById('add_here').removeChild(div.parentNode); } </script> <body> <form method='post' action='formaction.php'> Children <!-- Template. This first instance of "whatever" will be appended in the add_here div --> <div id="template"> <input type="text" name="child[]" placeholder="Child's Name" style="width:250px; margin-left:7px; margin-right:4px;"> <input type="text" name="title[]" placeholder="Title" style="width:250px; margin-left:7px; margin-right:4px;"> <input type="button" onClick="addField()" value="+"> </div> <!-- container to hold the dynamically added instances of "whatever" --> <div id="add_here"> </div> <input type='submit'> </form>