Jump to content

mac_gyver

Staff Alumni
  • Posts

    5,510
  • Joined

  • Days Won

    185

Everything posted by mac_gyver

  1. and this is how simple it is to use a prepared query with the PDO extension - // at the point of querying for and fetching the data $sql = "SELECT planets_name FROM planets p JOIN users u ON p.planets_starsystem = u.users_galaxyViewSystem WHERE planets_galaxy = ? AND planets_planet = ? AND users_id = ? "; $stmt = $pdo->prepare($sql); $stmt->execute([ $testowanaGalaktyka, $testowanaPlaneta, $user_id ]); $result_data = $stmt->fetchAll(); // at the point of outputting the data if(empty($result_data)) { echo 'There is no data to display.'; } else { foreach($result_data as $row) { echo $row['planets_name'].'<br>'; } }
  2. somewhere here - https://forums.phpfreaks.com/profile/211055-leonlatex/content/?type=forums_topic&change_section=1
  3. this is the same 'activity' as in your previous thread, just with different meaning columns. earlier thread - SELECT users_username FROM users u JOIN planets p ON u.users_id = p.planets_ownerid WHERE planets_galaxy = $testowanaGalaktyka AND planets_starsystem = $testowanySystem AND planets_planet = $testowanaPlaneta this thread - SELECT planets_name FROM planets p JOIN users u ON p.planets_starsystem = u.users_galaxyViewSystem WHERE planets_galaxy = $testowanaGalaktyka AND planets_planet = $testowanaPlaneta AND users_id = 1 you are SELECTing things FROM a table JOINed with another table ON some condition relating the data between the tables WHERE some list of conditions that all ANDed together must be true. the learning to be had here is learning the structure of the query, so that you can write new queries based on what you have done before. the following is the SELECT query prototype definition, which is listed in the order that the parts must appear within a query, with the parts you are using in bold (note: FROM table_references includes any JOINs) - SELECT [ALL | DISTINCT | DISTINCTROW ] [HIGH_PRIORITY] [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT] [SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS] select_expr [, select_expr] ... [into_option] [FROM table_references [PARTITION partition_list]] [WHERE where_condition] [GROUP BY {col_name | expr | position}, ... [WITH ROLLUP]] [HAVING where_condition] [WINDOW window_name AS (window_spec) [, window_name AS (window_spec)] ...] [ORDER BY {col_name | expr | position} [ASC | DESC], ... [WITH ROLLUP]] [LIMIT {[offset,] row_count | row_count OFFSET offset}] [into_option] [FOR {UPDATE | SHARE} [OF tbl_name [, tbl_name] ...] [NOWAIT | SKIP LOCKED] | LOCK IN SHARE MODE] [into_option] other common parts that you will see are - GROUP BY, occasionally HAVING, ORDER BY, and LIMIT. learning the meaning of and how to use these parts of a select query will allow you to write you own queries. note: most queries that will match more than one row should have an ORDER BY term so that the data will be in the order that you want it. next, you need to use a prepared query, with ? place-holders in the sql query for each value, then supply the actual values when the query is executed. this will prevent any sql special characters in a value from being able to break the sql query syntax, which is how sql injection is accomplished. since the mysqli extension is overly complicated when doing prepared queries, this would be a good time to switch to the much simpler and better designed PDO extension.
  4. to produce an array of the club checkboxes, the field name must be an array - name = "club[]"
  5. it initializes the variable to an empty array, in case the same variable was previously used in the current code and already has something in it that doesn't have anything to do with the current usage.
  6. the undefined error is due to this -
  7. while this (probably) isn't the cause of the problem, the Null Coalescing Operator ?? goes with the php variable, for the case where it won't exist when creating/inserting new data. value='<?= htmlentities($post['ConseilJour']??'',ENT_QUOTES)?>' what does the view source of the web page show? i suspect that the character(s) in question are not simple quotes that htmlentities operates on, leaving them as is, but are meaningful to the browser and are breaking the markup.
  8. this is the programming mistake - along with the fact that you are not validating that get input before trying to use it with an sql query.
  9. apply htmlentities(), with the ENT_QUOTES flag, when you output the value.
  10. so, if you are using the original function code, why did you remove the use of the ... splat operator?
  11. 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);
  12. 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.
  13. 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.
  14. 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?
  15. you should supply an associative ARRAY of ALL the data needed for the template.
  16. 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.
  17. 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.
  18. 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?
  19. 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.
  20. 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.
  21. 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.
  22. 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.
  23. 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/
  24. $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']...
  25. you would need to return $beneficiaries;, rather than to echo it, and then use the returned value in the calling code.
×
×
  • 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.