Jump to content

mac_gyver

Staff Alumni
  • Posts

    5,450
  • Joined

  • Days Won

    175

Everything posted by mac_gyver

  1. assuming the function code already exists and you don't want to change it, you can use php's splat ... operator to call the function with an array of values that will get expanded into the individual input parameters. $gift_fields = [77, 80, 65, 66, 67, 83, 74, 87, 88, 90, 92]; $params = []; foreach($gift_fields as $field) { $params[] = $form_data['field'][$field]; } echo SpecificGifts(...$params); if you rewrite the function code to accept and operate on elements of a single array input parameter, you would change the last line to - echo SpecificGifts($params);
  2. how are those array indexes 77, 80, ... determined, is that all the possible index values or just a sub-set of them, and what does the function code do with the input parameters? ideally, you would supply one array input parameter, with elements that are the set of input values. just based on the posted information, I would make an array of the index values, then loop to build the one array of inputs, then call the function with that array.
  3. that's not what i stated to do. if your code does not have validation logic for all inputs and error handling for all the statements that can fail with an error, you will forever be wondering why it doesn't work. the advice we give you is to help you make your code - more secure, provide a good user experience, be simple, general-purpose, maintainable, and through validation and error handling, will either work or it will tell you - display/log, the reason why it isn't working.
  4. a http 404 error is used if a requested web page doesn't exist. if a query doesn't match a 'required' input value, that's not a use for a http 404 error page. a query that doesn't match a required value is either due to - a programming mistake (which is the current cause), the matching row of data was deleted, or something is feeding your code their own input value that doesn't exist. when you are learning, developing, and debugging code/queries, your code/system should tell you why it is failing. does using a http 404 error page do that? doesn't that mean that you should instead be setting up and displaying a helpful error message?
  5. you should supply an associative ARRAY of ALL the data needed for the template.
  6. remove the action='...' attribute from the <form ...> tag to get the form to submit to the same page it is on AND automatically propagate any existing get parameters in the url. by specifying the URL in the action attribute with just the page name, there is no longer any user_id on the end of the url. before you go on, you should lay out the code on your page in this general order - initialization post method form processing get method business logic - get/produce data needed to display the page html document since you want to initially populate the form fields with the existing data, then if there are any user/validation errors in the form processing code, populate them with the submitted form data, i recommend that you copy and trim the $_POST data into the existing $member array, using one single line of code. you would also want to only query for and fetch the existing data if the form has never been submitted (the $member array will be empty), so that you don't keep replacing the values the user has taken the time to enter, with the original values. here's a laundry list of issues with this code - the $_GET[user_id] is a requirement for this code to work. if it's not set or it doesn't contain a valid integer > 0, that's an error and you should setup and display an error message on this page that a required input is not present/valid, and not even attempt to run the SELECT query. had there been code to do this, you would have been getting an error message that would have alerted you that the form wasn't including the existing $_GET['user_id'] in the url. likewise, if the SELECT query doesn't match any data, which would mean that either there's a programming mistake or that the row of data was deleted after the edit link was produced, you should you should setup and display generic message, on this page, for the user that's there's no data to edit. hopefully, when you are making the database connection you are setting the error mode to exceptions (along with setting the character set to match your database tables, setting emulated prepared queries to false, and setting the default fetch mode to assoc.) don't unnecessarily write out things for every possible form field. forget the $customers array variable, just reuse the $member variable as described above. just set the $errors to be an empty array and only put entries into it for actual errors. you can then just test if it is empty() or not empty() at any point to find if there are no errors or errors. there's no need for any else{} logic clearing an element in the $errors array, since you will only be setting an element in the $errors array if there was an error. all the input data you use in the post method form processing should come via post data. to get the customer_id/user_id into that code, pass it via a hidden form field. if 'required' inputs are empty, after being trimmed, that's a different problem from them being a wrong length or having a wrong format. you should first validate that required fields are not empty strings, before performing any other validation. at least the email column should be defined as a unique index. you need error handling for any insert/update query to catch and handle duplicate (or out of range errors.) the catch logic would test the error number and if it is for anything that the visitor can correct, setup a message telling them what exactly was wrong with the data that they submitted. for all other error numbers, just re-throw the exception and let php handle it. after the end of all the post method form processing logic, if there are no errors, redirect to the exact same url of the current page to cause a get request for that page. this will prevent the browser from trying to resubmit the form data. if you want 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. don't share the same variable for the error and the success message. at the point of displaying any error message in the html document, test if the $errors array is not empty.
  7. and if you do all of that, plus a bunch of fundamental things i didn't bother to write out, you should end up with code that looks like this (untested) - <?php // initialization session_start(); // used by success message $host = "localhost"; $username = "client"; $password = "client"; $dbname = "site";// On crée la connection PDO ici $DB_ENCODING = 'utf8mb4'; // db character encoding. set to match your database table's character set $options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // set the error mode to exceptions PDO::ATTR_EMULATE_PREPARES => false, // run real prepared queries PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // set default fetch mode to assoc ]; $dsn = "mysql:host=$host;dbname=$dbname;charset=$DB_ENCODING"; $pdo = new PDO($dsn, $username, $password, $options); $post = []; // array to hold a trimmed working copy of the form data and initially holds the data to be edited. $errors = []; // 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 input is an array, use a recursive trim call-back function here instead of php's trim // if there is a true id input, you are editing an existing row // if there is not a true id input, you are inserting a new row // validate inputs here... storing validation errors in the $errors array, using the field name as the array index // if no errors, use the input data if(empty($errors)) { if($post['id']) { // update existing row $sql = "update cercles set dates=?, Energie=? WHERE id = ?"; $stmt = $pdo->prepare($sql); $stmt->execute([ $post['dates'] ,$post['Energie'], $post['id'] ]); // if this query can result in duplicate or out of range data, handle that here and setup a message for the user letting them know what exactly was wrong with the data that they submitted // the current design assumes that there is only one row per dates. this column should be defined as a unique index // in which case inserting/updating a duplicate date will result in an error. } else { // insert new row $sql = "INSERT cercles (dates,Energie) VALUE (?,?)"; // set `dates`='[$newdate]',`Energie`='$Energie',`Planete`='$Planete',`JardinConseil`='$JardinConseil',`Ange`='$Ange',`Saint`='$Saint',`ConseilJour`='$ConseilJour',`Lune`='$Lune',`Soleil`='$Soleil',`TypeLune`='$TypeLune'"; $stmt = $pdo->prepare($sql); $stmt->execute([ $post['dates'],$post['Energie'] ]); // if this query can result in duplicate or out of range data, handle that here and setup a message for the user letting them know what exactly was wrong with the data that they submitted // the current design assumes that there is only one row per dates. this column should be defined as a unique index // in which case inserting/updating a duplicate date will result in an error. } } // if no errors, success if(empty($errors)) { // to display a one-time success message, store it in a session variable, then test, dusplay, and clear that variable at the appropriate location in the html document $_SESSION['success_message'] = "Les données suivant ont étaient mis a jour..."; // pour la date $newdate : $Energie-$Planete-$JardinConseil-$Ange-$Saint-$ConseilJour-$Soleil-$TypeLune"; // 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 $date = $_GET['date'] ?? date('Y-m-d'); // si aucun input, on met la date d'aujourd'hui par défault $days = $_GET['days'] ?? 0; // le nombre de jour par défault a 0 $dt = new DateTime($date); $newdate = $dt->modify("$days days")->format('Y-m-d'); // if the form has never been submitted, get any existing data to be edited - if(empty($post)) { //query // you should list the columns you are selecting // and build the sql query in a php variable $sql = "SELECT id, dates, Energie FROM cercles WHERE dates = ?"; $stmt = $pdo->prepare($sql); $stmt->execute([$newdate]); $post = $stmt->fetch(); } // html document ?> <html> <body> <?php // display the search form ?> <form> <button name='days' value='-1'>&lt;</button> <input type='date' name='date' value='<?=$newdate?>' > <button name='days' value='1' >&gt;</button> </form> <?php // display 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>'; } ?> <?php // display the edit/insert form if(empty($post['id'])) { echo "There is no existing data to edit, create a new entry:"; } else { echo "Edit existing data:"; } ?> <form method='post'> <input type='hidden' name='id' value='<?= $post['id'] ?? ''?>'> Date: <?=$newdate?><br> Changer la date : <input type='date' name='dates' value='<?= $post['dates'] ?? $newdate?>'><br> Energie: <input type='text' name='Energie' value='<?= $post['Energie'] ?? ''?>'><br> <input type ='submit'> </form> </body> </html> this is incomplete (no validation logic or error handling for duplicate unique database entries) and only operates on a few of the form fields. you need to get your logic to work at all before you worry about all the code and markup needed for all the form fields. in fact, if you have more than about 2-3 form fields, you should use a data-driven design, where you have a data structure (array, database table) that defines the fields, what validation there is for each field, and what processing will be done for each field, then loop over that definition to validate and process (build either the update or insert query) to dynamically do this rather than to write out code for every field.
  8. you have a get method (the default for a form without a method attribute) search form. where does that form currently have an opening <form> tag and where is its closing </form> tag? next, you have a post method edit (and insert) form. where does that form currently have an opening <form ...> tag and where is its closing </form> tag?
  9. of course. it's newly submitted data. it came from a source that's outside of your control. you validated the specific data that was submitted and used for the insert query. this has nothing to do with the data that was submitted at a different time for an update query. yes. programming IS a tedious, repetitious activity. this is why you need to always be on the lookout for ways of simplifying and reusing code, so that you end up being able to concentrate on the goal you are trying to achieve, rather then on the implementation details. the only real difference in the data between the insert and the update code is the update code will have an id value, that the insert code didn't have.
  10. i'm not sure what that means. external data submitted to your site can come from anywhere, not just your form, can be anything, and cannot be trusted. you must validate all input data before using it. it doesn't matter what the actual operation being performed on that data is.
  11. part of this issue is what your definition is of sanitize. i/we think of it as removing or eliminating the bad parts, e.g. to sanitize a surface to kill a virus on it. reread the rest of that paragraph. don't modify the actual piece of data, which changes the meaning of the data, then attempt to use it in your application. let me tell you a story about a prior version of this forum software. the authors of this code rolled their own email address sanitize function that removed characters that THEY thought should be removed, but which were actually valid in email addresses. this resulted in users being able to create a valid email address at the same domain as an existing email address, such as gmail, that after sanitization, matched the email address of an administrator. they were then able to do a password recovery for that administrator account but which used their own email address. a copy of the user data was stolen. applying htmlspecialchars/htmlentities to a piece of data when you output the value it in a html context, if only done at that point, is not modifying the actual data. it is converting any html special character to their html entities in the output, so that those html special characters cannot break the html syntax. yes. yes. only use the validate filters, not the sanitize filters. if data is valid, you can use it for its intended purpose in the application. if it is not valid, let the user correct what is wrong with it and resubmit it. if the user is a bot/hacker, the extra junk they include in a value won't pass validation, but after being removed by sanitization, would allow the application to proceed to use the value.
  12. perhaps if you make use of the information in the replies you have already gotten, so that we are not repeatedly writing the same answers in thread after thread? the replies forum members have written, after taking the time to read what you are doing, are to help you make your code - more secure, provide a good user experience, be simple, general-purpose, maintainable, and through validation and error handling, will either work or it will tell you - display/log, the reason why it isn't working.
  13. you are still wasting time writing out hundreds of lines of code that are copying variables to other variables for nothing. go back and (re)read the replies i wrote about using a data-driven design, what other settings you should use when you make the connection, and about only catching and handling database exceptions for things the visitor to your site can recover from - https://forums.phpfreaks.com/topic/315008-information-not-updating-to-database-after-deselecting-a-checkbox/
  14. $form_data doesn't exist inside the function (there would be php errors.) you could actually just define the function to accept an array of data as the input and call the function with $form_data['field'][77] as the input parameter. this will allow the processing to be applied to any array of data, not hard-coded for $form_data['field']...
  15. you would need to return $beneficiaries;, rather than to echo it, and then use the returned value in the calling code.
  16. $arr[0] is the first row of data, which is an array. to 'reference elements in it' would look like $arr[0]['store_name'], $arr[0]['address'], ... you can always use print_r() or var_dump() on variables to see what they hold. if current($arr[0]) resulted in the store name, that means that the store name is the first column in the SELECT ... list. the id column in any database table should be an autoincrement primary index, which is unique, i.e. each different store, regardless of the name will have have its own id value. when i stated to select the store id as the first column being selected in order to make this work, this is the column i meant. if you don't have an autoincrement primary index column, you need to add it. if you then select this as the first column in the SELECT ... list, the method i have posted will work for multiple stores, even with the same name.
  17. substr() deals with single byte characters. try mb_substr()
  18. one of the file uploads is failing, but because you don't have error checking and validation logic, you don't know if or why it is failing. the post method form processing code should - detect if a post method form has been submitted. do not attempt to test if the submit button is set. if the total size of the form data exceeds the post_max_size setting, both the $_POST and $_FILES arrays will be empty. you need to test for this condition and setup a message letting the user know that the form data was too large and could not be processed. if there is $_FILES data, you need to test the ['error'] element of each file to make sure it uploaded without any error before using any of the file data. there's a list of the error values at https://www.php.net/manual/en/features.file-upload.errors.php don't copy variables to other variables for nothing. this is just a waste of your time typing. just use the original variables. you need to validate all input data before using it, storing validation errors in an array using the field name as the array index. if an input is 'required' and it is an empty string or it must have a specific format, setup a unique message for each validation error telling the user what was wrong with the data value. after the end of all the validation logic, if there are no errors (the array holding the errors will be empty), use the submitted form data. using a prepared query (the PDO database extension is much simpler to use than the mysqli extension), insert the data and get the last insert id from that query. use the id as the file part of the filename. as already mentioned, user submitted data can be anything and should be carefully used or in this case not used at all as part of the filename.
  19. the key to updating an existing row or inserting a new row is the existence or absence of an id (autoincrement primary index) in the form data. if your database table doesn't already have an id/autoincrment column, add it. when you query to get the existing data to edit, add this column to the SELECT ... list (you should actually list out the columns you are selecting, rather than use *). output the id in a hidden form field. in the form processing code, if the id input is a true value, execute the code for an UPDATE query. if it is not a true value, execute the code for an INSERT query. to handle both having existing data to edit or no data, you should have an intermediate array variable, such as $post, that will initially hold any existing data that you fetch from the SELECT query, then inside the post method form processing code be assigned a trimmed copy of the $_POST form data. in the form value attributes, use php's null coalescing operator (??) to output the corresponding $post value or an empty value - Energie: <input type='text' name='Energie' value='<?=$post['Energie'] ?? ''?>'><br>
  20. the reason the date isn't being used in the first type='date' field is because that's already a php string. don't use <?= ?> tags around the variable, just use the $newdate variable - <input type='date' name='date' value='$newdate' > next, nested forms are invalid. the date search form needs to be closed with a </form> tag, before you start the next form. several of the form fields have the same name, so, only the value from the last one will be used. the post method form processing code should be on the same page as the form. this will simplify all the code and allow you to repopulate the field values if there is a user/validation error in the form processing code. all those lines of code copying one variable to another is a waste of your time typing. just use the original variables. why on earth are you using the PDO database extension to get the existing data to be edited, then using the mysqli database extension in the post method form processing code? just use the much simpler PDO extension everywhere. also, use a prepared query for the UPDATE query and the UPDATE query needs a WHERE clause so that you are updating the correct row. lastly, if there can be more than one row per date, you need to loop to fetch and produce the edit form(s) with either one total form or one form per row and you would need to use an id (autoincrement primary index) to determine which row to update.
  21. then $_POST['submit'] is likely not set and that block of code isn't running or you have some code that you didn't post that's setting it to null. do you have php's error_reporting set to E_ALL and display_errors set to ON, preferably in the php.ini on your system, so that php would help you by reporting and displaying all the errors it detects? you should be getting an undefined variable error for $mentor and another error at the foreach() statement about it being null. next, a post method form is using when performing an action on the server, such as inserting, updating, deleting data, or sending an email, ... Yo should be using a get method form/link for searching for data to display.
  22. i suspect the error is due to exceeding some limit at your free/cheap web hosting - you might ask their support group. already stated -
  23. see if the web server error log contains any additional information. you should be using a localhost development system when learning, developing, and debugging code/query(ies). doing this on a live/public server wastes a bunch of time constantly uploading files to see the result of each change and since your code is not secure, can allow someone to abuse your web hosting. only put complete, secure code onto a live/public web site.
  24. also, if you are just starting out, learn and use the much simpler and better designed PDO database extension. don't put data values directly into an sql query statement. you should be using a prepared query when supplying external, unknown, dynamic values to the query when it gets executed.
  25. while this isn't the cause of the problem, you need to validate the resulting web page(s) at validator.w3.org you cannot spread the markup for a form throughout a html table. you can put a compete html table inside a form and you can put a complete form inside a single table data cell <td>...</td>, but you cannot intermix the markup for a table and a form. also, the form and form processing code should be on the same page. this will simplify all the code. the code for a 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 post method from processing code should - detect if a post method form was submitted. keep the form data as an array variable, then operate on elements in this array variable throughout the rest of the code. trim all the inputs at once. when you do item #2 on this list, you can trim all the data using one single line of code. 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 the array holding the errors is empty, use the submitted form data. an insert/update query can result in duplicate data for things that must be unique, such as a username or email column. your code should handle query errors in these cases. the simplest way of doing this is to use exceptions for database statement errors and have exception try/catch logic only is these cases. the catch logic would test the error number and if it is for something that the visitor can correct, setup a message telling the visitor exactly what was wrong with the data that they submitted, so that they can potentially submit new value(s) that will succeed. for all other error numbers, just re-throw the exception and let php handle it. after the end of the form processing logic, if there are no errors, redirect to the exact same URL of the current page to cause a get request for the page. this will prevent the browser from trying to resubmit the form data should the visitor reload the page or navigate away from and back to that URL. if you want 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. if there are errors at item #5 on this list, the code would continue on to display the html document, display any errors, redisplay the form, populating the field values with any existing data. any dynamic value you output on a web page should have htmlentities applied to it to help prevent cross site scripting. the http 405 error means you are using a method that isn't supported or configured correctly. this isn't being cause by anything you are doing with the database server. what is the actual URL of the form page and what is the url in the browser's address bar after you submit the form? as a test, to see if just a basic form will work, make a new .php page with the following and test it - <?php echo '<pre>'; print_r($_POST); echo '</pre>'; ?> <form method='post'> <input type='text' name='somefield'> <input type='submit'> </form> after you submit the form, the print_r output should show an array with the field name as an index and whatever value you type into the field.
×
×
  • 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.