Jump to content

mac_gyver

Staff Alumni
  • Posts

    5,064
  • Joined

  • Days Won

    160

mac_gyver last won the day on November 17

mac_gyver had the most liked content!

2 Followers

About mac_gyver

Profile Information

  • Gender
    Not Telling

Recent Profile Visitors

150,719 profile views

mac_gyver's Achievements

Prolific Member

Prolific Member (5/5)

583

Reputation

97

Community Answers

  1. it would probably be better if you continued any posting about this subject in the Nov 15th thread - https://forums.phpfreaks.com/topic/315539-is-anything-wrong-with-this-code/ that came after the last Nov 13th post above. the outline of code for the form/form processing that i gave in that thread produces no errors when it runs. this should have eliminated much of the work of getting to the point of having all the input data ready to use in the calculations. i also see though looking at your previous threads that several of the suggestions recently given were previously given but never used.
  2. the processing of the submitted post method form data should have nothing directly to do with the display of any data. you should - display the form when the form is submitted, detect if a post method form has been submitted trim, then validate the form data, storing any user/validation errors in an array using the field name as the array index if there are no user/validation errors, use the form data (which could result in more user errors, such as for duplicate or out of range values) if here are no errors at this point, redirect to the exact same url of the current page to cause a get request for the page to display a one-time success message, store it in a session variable, then test, display, and clear that session variable at the appropriate location in the html document at this point, you would get any data needed to display the current page, then output it in the html document. if you want the user to be able to go to different page(s), that queries for and displays other data, provide navigation link(s) to do so.
  3. the new-line/end-of-line setting in your programming editor is set to a non-standard setting. changing it to any of the other choices would be an improvement and allow the forum software to display your code properly.
  4. you would need to run the php script at 1.5 minute intervals (twice the frequency of the data) to insure that you don't miss any data. you would read the contents of the file and explode it into an array. if you want to only keep some of the elements, you can use array_intersect_key() to only keep those elements that you want. to store the data, rather than to have a table with 177+ columns, have one table which you insert a row for each data sample, with an id (auto-increment primary index), a datetime column, and any other columns that describe the data, such as a unit id, so that you can record data for multiple stations. the id column in this table produces a data_id. you would get this id and use it when storing the actual data. the data table would have an id (auto-increment primary index), data_id, field number (0-177), and value columns. the icon mapping values would be stored in another database table, that you would JOIN with the field number 48 values to get the corresponding text/image.
  5. what your code should do for this activity is generate a random number, then do what is described in this post - https://forums.phpfreaks.com/topic/315552-php-mysql-returns/#comment-1602746 to just attempt to insert that random number into the table. if the code continues past the point where the INSERT query is executed, you know that the generated number was unique and was inserted into the table. if the code transfers execution to the exception catch block and the error number is for a duplicate index, instead of setting up a message for the user that there was a duplicate, you would cause the code to loop back to the start, where it would generate a new random number and attempt to execute the insert query again. i would use a loop counter, of about 10, so that a programming mistake or the random number generator doesn't work very well (the rand() documentation mentions that the maximum on windows is a 32bit number, not a double-int) to force an exit if the operation doesn't succeed.
  6. the OP is trying to do this activity by rote, by memorization, by appearance, not though actually learning (internalizing) the meaning of the words and syntax. this produces a result that is only as good as his memory recall is. the mysqli_query() call on the prepared query statement object is the same misusage at the start of a previous recent thread, which @requinix hinted/asked (Jeopardy theme can be heard playing in the background) if the OP actually wanted to do this. one would assume that since the OP removed this statement in that thread that he would have learned something by doing so, but since the OP is doing this by repeating pictures of the words, no learning occurred, hence the repeated mistake. @alexandre, writing code actually means writing the words and syntax of the language you are using, so that they result in an understandable story that when the computer executes them they do something useful. to do this you must actually learn the meaning of the words and syntax, not just repeat, copy/pasting things together based on what you have seen. somehow, you must make this transition in how you are approaching this activity. instead of just seeing and repeating a picture of the words, you must actually learn the meaning of the words, so that you know what they do or even if they belong in the current task.
  7. your database design must enforce uniqueness, it is the last step in the process. when there are multiple concurrent instances of your script running, they can all query to find that the value does not exist and attempt to insert it. the first one will win this timing race and succeed. all the following ones must fail with an error. to do this, the column you are trying to match must be defined as a unique index. you would then just simply attempt to insert the data and in the error handling, which should be using exceptions, you would test if the error number is for a unique index violation (1062), and setup a message letting the user know that the value is already in use. for all other error numbers, just rethrow the exception and let php handle it.
  8. you are using a post method form, followed by an unnecessary redirect, to select which record to edit and then a get method form for updating the data. this is backwards. you should use get inputs to determine what will be displayed on a page and a post method form when performing an action on the server, such as updating the data. also, you can and should do all of this on one page to avoid repetition of code. the code for any page should be laid out in this general order - initialization post method form processing get method business logic - get/produce data needed to display the page html document when you display the existing records, the edit button should be a get method link with the id as part of the link. when you click one of those links, the resulting code that gets executed would query to get the existing row of data to populate the form field values, but only if the update form has never been submitted. if the update form has been submitted, you would not execute this query. the way to accomplish this 'interlocking' of the data being edited is to use an internal 'working' array variable to hold this data, then use elements in this array variable through out the rest of the code. inside the post method form processing logic, you would store a trimmed copy of the $_POST form data in this variable. at the point of querying for the initial data, if this variable is empty, you would execute the query. here are some issues with and things that will simplify the posted code - your login system should only store the user id in the session variable upon successful login, then query on each page request to get any other user information, such as the user's name, permissions. your code should check if the current logged in user is an admin before allowing access to the edit logic. when conditional 'fail' code is much shorter than the 'success' code, if you invert the condition being tested and put the fail code first, it results in clearer, cleaner code. also, since the fail code is a redirect in this case, which must have an exit/die statement to stop php code execution, you can eliminate the else {} part of the conditional test since the redirect/exit/die will stop the execution for a non-logged in user. don't copy variables to other variables for nothing. this is just a waste of typing and introduces errors. don't use multiple names for the same piece of data. whatever the actual meaning of the data is, use that name throughout the code. one such example is the staff_id value being called 'data' and at another point it is a name value. since you will be switching to use a post method form for the update operation, after you detect if a post method form has been submitted, all the form fields (except for unchecked checkbox/radio fields) will be set. there will be no need for a massive list of isset() statements. you should put the database connection code in a separate .php file, then require it when needed. you should not unconditionally echo database errors onto the web page, which will only help hackers when they internationally trigger errors. instead, use exceptions for database statement errors an in most cases let php catch and handle the exception. the exception to this rule is when inserting/updating user submitted data that can result in duplicate or out of range values, which is something that you are doing. in this case, your code should catch the exception, test if the error number is for something that your code is designed to handle, and setup a message letting the user know what was wrong with the data that they submitted. for all other error numbers, just re-throw the exception and let php handle it. the logout operation should use a post method form. any function definitions should either be in the initialization section of code or be in their own .php files that get required in the initialization section of code. your application should not use the root user without any password. instead, create a specific database user with a password with only the permissions that it needs for you application. the updateRecord function should only have two call-time parameters. an array of the input data and the database connection. the updateRecord should not contain any application specific html markup. this should be handled in the calling code. the function should only return a true or false value to the calling code. don't put external, unknown, dynamic values directly into sql query statements. you must protect against sql special characters in data values from being able to break the sql syntax, which is how sql injection is accomplished. the fool-proof way of doing this is to use prepared queries. since the mysqli extension's prepared query interface is overly complicated and inconsistent, this would be a good time to switch to the more modern and simple PDO database extension. the updateRecord function should not close the database connection. it is not the responsibility of this function to do this, only to update the recorded. the update form should populate the form field values and preselect the option that matches the initial existing data being edited, then populate/preselect using the submitted form data, as described above. any dynamic value that you output on a web page should have htmlentities() applied to it to help prevent cross site scripting. the value attribute for the select/option 1st prompt option should be an empty string. since you are putting the <label></label> tags around the form field they belong with, you don't need the for='...' and matching id='...' attributes. the post method form processing code should - detect if a post method form was submitted. keep the form data as a set in an array variable. trim all the input data as at once. after you do item #2 on this list, you can do this with one php statement. validate all the inputs, storing validation errors in an array using the field name as the array index. after the end of all the validation logic, if there are no errors, use the form data. after using the form data, if there are no errors, redirect to the exact same url of the current page to cause a get request for the page. if you want to display a one-time success message, store it in a session variable, then test, display, and clear the session variable at the appropriate location in the html document. if there are errors at step #5 or #6 on this list, the code would continue on to display the html document, where you would test for and display any errors, and redisplay the form, repopulating the field values/selected option choices with the values that are in the 'working' array variable holding the submitted form data.
  9. foreach(array_keys($matches[1]) as $key) { echo "SKU number {$matches[1][$key]} costs {$matches[2][$key]}<br>"; }
  10. you should have one login system with a single set of ids. if your user login system and admin login system reuses ids, those users having ids the same as an admin will appear to be the admin with that same id. Keep It Simple.
  11. so, now you have to maintain two almost identical pages, where every change you make to the poll output, must be repeated in both pages. that's the wrong direction to move toward when doing programming. you want to reduced the amount of work you have to do to create and maintain a web site, not increase it. what's wrong with adding a simple conditional test where the two links appear at in the html document, so that they are only output if the current user is an admin? Keep It Simple (KISS.) edit: i also recommend that you convert your mysqli based code to use PDO. it is very simple to do so and actually eliminates a bunch of lines of code. you will also be able to directly fetch the result from the query into an appropriately named array variable, such as $user_data, so that you don't need to worry about naming a bunch of variables to keep from overwriting other variables that may already exist.
  12. now that we know a bit more about what you are doing, a multi-page form, collecting data that eventually gets used for some purpose, now would be a good time to switch to using a data-driven design, to eliminate all the repetitive code for the data collection, rather than to spend time fixing each page of it.
  13. i was able to make the code repopulate the fields/select-option, when navigating around, using 3 lines of code and one conditional test, added to the get method business logic section. i won't post the code i came up with because it is probably not how your application is determining which step/page it is on. you could also just merge the successful $post data into the $_SESSION['step'] array inside the post method form processing code, then when the page is visited without any $post data, copy the whole $_SESSION['step'] array back into $post (which i just tested and it works as well.) if you want help with anything your application is or is not doing, you must post enough of the code so that someone here can reproduce what it is doing.
  14. for the activity you have shown in this thread and using the previously given programming practices about how to organize, cleanup, and code your form processing and form, a lot of this typing of code goes away, you would end up with the following - <?php /* put any error relating settings in the php.ini on your system you may have a need to store the result from some step in session variable(s), but by unconditionally storing each piece of post data, you are doubling the amount of code needed. only store the end result. Keep It Simple (KISS.) to dynamically generate a select/option list, you would not use discrete variables for each value and write out logic for each option. you would instead have an array of the values, then loop to dynamically build the options. in html5, an empty action='' attribute is not valid. to get a form to submit to the same page it is on, leave the action attribute completely out of the form tag. you should validate your resulting web pages at validator.w3.org */ // initialization session_start(); $post = []; // an array to hold a trimmed working copy of the form data $errors = []; // an array to hold user/validation errors // post method form processing if($_SERVER['REQUEST_METHOD'] === 'POST') { // trim all the data at once $post = array_map('trim',$_POST); // if any of the fields are arrays, use a recursive trim call-back function here instead of php's trim function // validate inputs if($post['owner'] === '') { $errors['owner'] = 'The owner is required.'; } if($post['renter'] === '') { $errors['renter'] = 'The renter is required.'; } if($post['state'] === '') { $errors['state'] = 'The state is required.'; } // add validation for other inputs here... // if no errors, use the form data if(empty($errors)) { // if this is a step in a multi-step process, store the now validated data in a specific session variable $_SESSION['step'][1] = $post; } // if no errors, success if(empty($errors)) { // if you want to display a one-time success message, store it in a session variable here, // then test, display, and clear that session variable at the appropriate point in the html document $_SESSION['success_message'] = 'Some success message for this step in the process'; // redirect to the exact same url of the current page to cause a get request for the page die(header("Refresh:0")); } } // get method business logic - get/produce data needed to display the page // query to get the states in the order that you want them // fake some values $states = []; $states[]="Maine"; $states[]="Texas"; // html document ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Form processing/form example</title> </head> <body> <?php // display and clear any success message if(isset($_SESSION['success_message'])) { echo "<p>{$_SESSION['success_message']}</p>"; unset($_SESSION['success_message']); } ?> <?php // display any errors if(!empty($errors)) { echo "<p>".implode('<br>',$errors)."</p>"; } ?> <form method="post"> <label>Owner: <input type="text" style="width:255px;" name="owner" value="<?=htmlentities($post['owner']??'',ENT_QUOTES)?>"></label><br> <label>Renter: <input type="text" style="width:255px;" name="renter" value="<?=htmlentities($post['renter']??'',ENT_QUOTES)?>"></label><br> <label>State: <select name="state"> <option value="">select state</option> <?php foreach($states as $state) { $sel = isset($post['state']) && $post['state'] === $state ? 'selected' : ''; echo "<option value='$state'$sel>$state</option>"; } ?> </select></label><br> <input type="submit"> </form> <?php // note: if you have the need for a 'clear' session function, add that as a separeate post method form, with a hidden field with a value to indicate that action // then test for that action value in the form processing code to clear the session data ?> <?php // display the content of the session if(!empty($_SESSION)) { echo '<pre>'; print_r($_SESSION); echo '</pre>'; } ?> </body> </html> and as already mentioned, if you have more than 2-3 form fields, you should use a data-driven design, where you have a data structure (database table, array) that defines the expected form fields (for each step), validation rules, and processing for each field, then dynamically validate and process the form data, rather than to write out bespoke logic for each field.
  15. the following is a 'tricky' example of INSERTing data that satisfies a maximum count of rows - $query = "INSERT INTO team_members (team_id, staff_id, stafftype) SELECT -- the following values being SELECTed are the actual data values to insert ?,?,? FROM DUAL -- dual is an allowed dummy table name to satisfy the FROM ... WHERE syntax WHERE (SELECT COUNT(*) FROM team_members WHERE team_id = ? AND stafftype='leader') < 1 -- insert the data if the WHERE (subquery count) < 1 is TRUE"; $stmt = $pdo->prepare($query); $stmt->execute([$team_id, $staff_id, $stafftype, $team_id]); if($stmt->rowcount()) { echo "A leader row was inserted for team_id: $team_id, staff_id: $staff_id<br>"; } else { echo "A leader already exists for team_id: $team_id<br>"; } this example was to insert a maximum of one 'leader' row per team id. you would change it to insert a maximum of two rows per datetime appointment slot. because this uses a single query to both get a count of the number of existing rows and insert a new row, it will work correctly for multiple concurrent instances of your script.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.