Jump to content

mac_gyver

Staff Alumni
  • Posts

    5,510
  • Joined

  • Days Won

    185

Everything posted by mac_gyver

  1. php variables are case sensitive. $_SESSION['test'] is not the same as $_SESSION['Test']. you would have been getting a php error to alert you to the problem. do you have php's error_reporting set to E_ALL and display_errors set to ON, preferably in the php.ini on your development system, so that php will help you by reporting and displaying all the errors it detects? you will save a ton of time. most of the form markup is broken, and it's doubtful that you even have some of the shown input data. you need to trim, then validate all inputs before using them. if a 'required' input is not valid, that's an error and you should setup and display a user message rather then blindly attempting to use non-existent data. you should validate the resulting web pages at validator.w3.org to help find the mistakes in the markup. the user errors you do have are also not preventing the code needing the inputs from running, likely producing php errors and no result. $display_block is being overwritten by later code, so any user errors you may have setup are being lost. you need to store user/validation errors in an array, using the field name as the array index, then only use the input data if the array holding the errors is empty.
  2. i was able to get the view page to display red, but could not get the audio file to play (probably a browser permission or timing issue.) i recommend adding logging code in both the alert and alert_generate files, with datetime, file, and action being performed so that you can see what the code is actually doing. for what this code is doing, there's about three times too much code and most of the markup is out of date, and even when it wasn't there's a huge amount of broken html present. if you rewrite it, the major things that will simplify it are - put the form processing code and the form on the same page. there's no need for the alert.php file, the ajax request to it, and requesting it when the submit button is pressed (which doesn't even mean that the form got submitted.) at the point of successfully completing the post method form processing code, you would set the alert status flag in the row in the alert database table. there's also no need for the alert_generate.php file and the ajax requests to it at 300 millisecond intervals. you are already causing the view page to be periodically reloaded. if the alert status flag is set when the page is requested, just output the markup needed to cause the page to display red, play the audio file, and reset the alert status flag. as already stated, put the database connection code into a separate .php file and require it when needed. switching to the much simpler and more modern PDO extension will simplify all the database code. the only time handling database statement errors in your application code will do any good are for user recoverable errors, such as when inserting/updating duplicate or out of range user submitted values. since you are not dealing with these (you should use a run-once token to prevent multiple form submissions), there's no need for any database error handling logic in your code. just use exceptions for database statement errors and let php catch and handle any exception, where php will use its error related settings to control what happens with the actual error information (database statement errors will 'automatically' get displayed/logged the same as php errors.) the code for any web page should be laid out in this general order (this would apply to the form processing/form page and the view page) - initialization post method form processing get method business logic - get/produce data needed to display the page html document the form processing/form page should - detect if a post method form was submitted. keep the form data as a set in a php array variable, then operate on elements in this array throughout the rest of the code, i.e. don't write out lines of code copying each form field to other variables for nothing. trim all the input data before validating it. after you do item #2 on this list, you can accomplish this with one line of code. validate all the inputs at once, storing validation errors in an array using the field name as the array index. note: there is no 'song' field in the form and those lines of code you have for it in the form processing code are/should be producing php errors. after the end of all the validation logic, if there are no errors (the array holding the errors will be empty), use the form data. use a prepared query when supplying external, unknown, dynamic values to the query when it gets executed. after using the form data (since that code could produce additional errors, if there are no errors, perform a 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 the session variable at the appropriate location in the html document. it is at this point where you would set the alert status flag in the alert database table. if there are errors at step #5 or #7, the code will continue on to display the html document, display any errors, redisplay the form, populating the field values with the existing data. any value you output in a html context should have htmlentities() applied to it to help prevent cross site scripting. you should validate the resulting web pages at validator.w3.org
  3. how many rows are in the alert database table? this nonsense code assumes that there is one row of data, with an id of 1, is using a loop to retrieve the data from the table, and isn't doing anything to insure that the single expected row exists.
  4. the following is the only documentation that i found - https://www.godaddy.com/help/send-form-mail-using-an-smtp-relay-server-953 so, first question, which type of hosting do you have, since it determines what hostname you use? next, you can get the phpmailer to use php's mail() by calling the isMail() method, instead of the isSMTP() method. if using the isMail() method, you would not use any of the settings. if using the isSMTP() method, i would not use the username and password settings.
  5. your current code will always only output one form field, because count($hasil) is zero, and there's nothing in your code to cause more form fields to be output. if you are attempting to provide a way of entering a dynamic amount of data, this is typically done by outputting one form field, then using javascript to add a new (set of) field(s) upon pushing a button. if you want to do this without using javascript, you need to decide the maximum number of fields you want, then use that number to control the looping.
  6. just post all your current code so that someone can actually help with what it is or is not doing, rather than guessing based on snippets of information.
  7. you need error handling for ALL the database statements that can fail - connection, query, prepare, and execute. you currently don't have any error handling for the execute call, which would be telling you why the query is failing at execution time. the easiest way of adding error handling for all the database statements, without adding logic at each one, is to use exceptions for errors and in most cases simply let php catch and handle the exception, where php will use its error related settings to control what happens with the actual error information (database statement errors will 'automatically' get displayed/logged the same as php errors.) this will allow you to remove the existing error handling logic, since it will no longer get executed upon an error. the exception to this rule is when inserting/updating duplicate or out of range user submitted data. in this case, you would catch the exception in your code, test if the error number is for something that your code is designed to handle, and setup a unique and helpful error message letting the visitor know what was wrong with the data that they submitted. for all other error numbers, just rethrow the exception and let php handle it. to enable exceptions for errors for the mysqli extension, add the following line of code before the point where you make the database connection, and remove the existing error handling logic you have now - mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
  8. the nested data structures and the statement of 'arbitrary expressions' indicates that you are expected to write a recursive function to do this and since you wouldn't have been given this assignment without first having covered recursive functions, what information has been covered prior to this assignment?
  9. no display/a blank page from a php script is usually due to fatal parse errors or fatal runtime errors. this is throwing a fatal error, since $up_user is an object, $user doesn't exist, and you are trying to get the ->wallet property of that object. the likely (since we don't know the backstory about what you are doing) syntax should be $uploader_wallet = $up_user->wallet; do you have php's error_reporting set to E_ALL and display_errors set to ON, in the php.ini on your system so that php will help you by reporting and displaying ALL the errors it detects? you will save a ton of time.
  10. you have far too much code for this task. it is filled with repetitive logic, copying of variables to other variables for nothing, and while it is adding user/validation errors to an array, it isn't testing that array for the main activity of executing the INSERT query, which is why it is always inserting the new data values. i recommend that you start over, with just the logic you need - Keep It Simple (KISS) and Don't Repeat Yourself (DRY.) you should make one database connection in your main code, then supply it to any function that needs it, as a call-time parameter. you should use the much simpler and more modern PDO database extension. you should also use exceptions for database statement errors (the PDO extension always uses exceptions for any connection error and starting with php8 always uses exceptions for the rest of the statements that can fail - query, prepare, execute, and exec.) your post method form processing code should - detect if a post method form has been submitted keep all the form data as a set, in a php array variable trim all the input data at once. after you do item #2 on this list, you can trim all the data using one single line of code validate each input separately, storing user/validation errors in an array, using the field name as the array index after the end of the validation logic, if there are no errors (the array holding the errors will be empty), use the submitted form data as already stated, the correct way of determining if uniquely defined database columns/fields are duplicate, is to just attempt to insert the data and test if the query produced a duplicate index error number in the exception catch logic. for all other error numbers, just rethrow the exception and let php handle it. since you have more than one unique field, it is at this point where you would execute a (one) SELECT query to find which fields contain duplicate values. you would add error messages to the array holding the user/validation errors for each field that is found to contain duplicate values. after the end of 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 the page 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 step #5 or #7, the code will continue on to display the html document, display any errors, redisplay the form, populating the fields with any existing form data. any dynamic value that gets output in a html context needs to have htmlentities() applied to it to help prevent cross site scripting.
  11. due to things like cross site scripting and phishing attacks, even if this form and form processing code is only accessible to logged in users, the data submitted can be anything, cannot be trusted, and must be used securely in every context (sql, html, mail header, file operation.) a lot of web sites have been taken over due to injected code in values that were 'only being viewed by staff members'. the posted code example is - insecure (the current problem), provides a poor user experience (when there are validation errors, which the code doesn't even perform, by putting the form and form processing code on separate pages, requires the user to keep reentering data over and over), is filled with copying of variables to other variables for nothing, and has error handling for the database statement that would only confuse the visitor. prepared queries are the simplest, fool-proof way of preventing any sql special characters in a value, a ' in this case, from breaking the sql query syntax. however, the mysqli database extension is overly complicated and inconsistent when dealing with prepared queries. you would want to switch to the much simpler and more modern PDO database extension. the form processing code and form should be on the same page. this will reduce the amount of code that must be written, allow any user/validation errors to displayed with the form, and allow previously entered data values to repopulate the form fields so that the user doesn't need to keep reentering data upon an error. you should use exceptions for database statement error handling and only catch and handle the exception in your code for user recoverable errors, such as inserting/updating duplicate or out of range user submitted values. in all other cases, simply let php catch and handle the exception, where php will use its error related settings to control what happens with the actual error information (database statement errors will 'automatically' get displayed/logged the same as php errors) requiring no logic in your code at all. for more than about 2-3 form fields, you should use a data-driven design, where you have an array that defines the expected fields, validation steps, and processing, that you would simply loop over using general purpose code, rather then writing out, testing, debugging, and maintaining a bunch of bespoke code for every possible field.
  12. when i tried your code, $headerData being used when the query is executed is the full 'Battery-0975GJ' value. this is a string, not an integer. you are casting it as an integer in the bind_param("si" usage, resulting in a zero for a value. in sql queries, when one parameter in a comparison is a number, the other parameter is converted to a number as well. you are getting WHERE 0 = 0 which is matching every row.
  13. what is the number being inserted? do you have error handling for all the database statements that can fail - connection, query, prepare, and execute? are any of the columns in this table defined as unique indexes and could be producing a duplicate index error, that you are not handling? does your table have a datetime field that automatically gets the current datetime so that you would know when the data you see was actually inserted? BTW - this series of insert/update queries must be part of a transaction, so that you will only commit them if they all succeed without any errors, and will roll them back (or withhold committing them) if there's an error in any of them.
  14. any edit/delete link/form controls and any edit/delete operation code would be conditioned by either the current user's admin permission level or the current user's id matching the owner id of the data being edited/deleted. your login system should store the user's id in a session variable to indicate who the currently logged in user is. on each page request, you would query to get the current user's permissions (this is so that any change made to the permission level will take effect on the very next page request.) any stored data related to the user, such as blog posts, should use the user's id, not the user's username, to relate it back to the user (this is so that you can edit the username without needing to update all the related data to match the changed username value.)
  15. the posted code has a session_start near the top, then another one inside the post method form processing, right before assigning the last insert id to a session variable. the one near the top is all you need and in fact the second one will be producing a php error, which is probably being discarded when the redirect occurs. i would set php's output_buffering to off in the php.ini, so that you will see any non-fatal php errors or debugging output from your code prior to a redirect.
  16. the following is an example, with one 'email' type field, showing the organizational and post method form processing/form points that were made - <?php // initialization session_start(); $post = []; // array to hold a trimmed working copy of the form data $errors = []; // array to hold user/validation errors // post method form processing, detect if a post method form has been submitted 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 // validate inputs if($post['email'] === '') { $errors['email'] = "Email is required."; } else if(!filter_var($post['email'], FILTER_VALIDATE_EMAIL)) { $errors['email'] = "Email format is not valid."; } // if no errors, use the form data if(empty($errors)) { // use the data in $post here... } // if no errors, success if(empty($errors)) { $_SESSION['success_message'] = "Some success message."; die(header("Refresh:0")); } } // html document starts here... ?> <?php // output and clear any success message if(isset($_SESSION['success_message'])) { echo "<p>{$_SESSION['success_message']}</p>"; unset($_SESSION['success_message']); } ?> <?php // output any errors if(!empty($errors)) { echo "<p>".implode('<br>',$errors)."</p>"; } ?> <?php // output the form, repopulating any field values with the existing form data ?> <form method='post'> <label>Email: <input type='email' name='email' value='<?=htmlentities($post['email']??'',ENT_QUOTES)?>'></label><br> <input type='submit'> </form> your original logic, checking if it is set and assigning one value if it is, and another if it is not, is okay. i wouldn't make a new name/change the name for it when doing so, and you can use php's ternary operator to simplify the logic - // condition checkbox input $post['orderPaid'] = isset($post['orderPaid']) ? 1 : 0; by definition, all external data are string data types, regardless of what value they contain. if the 1st value='' option is selected, you will get an empty string in the php code. if one of the other options is selected, you will get a string containing the numerical value. as long as the string value only contains numerical characters, it should be handled okay by php and by the database. to actually validate that the non-empty submitted value is one of the permitted choices, i would make an array of the data from the tbl_countries select query, with the id as the array indexes, and the element values being the country names, then either test if the array entry corresponding to the submitted value isset() or testing if the submitted value is in the array of the array keys, using in_array() and array_keys().
  17. the main problem with the current code is that it doesn't have any 'working' error handling for the insert query. the error handling you do have for that query is testing if the sql query statement, which is a string, is a true value, which it always will be. instead, use exceptions for database statement error handling and only catch and handle the exception for user recoverable errors, such as when inserting/updating duplicate or out of range user submitted data values. in all other cases, simply let php catch and handle the exception, where php will use its error related settings to control what happens with the actual error information (database statement errors will 'automatically' get displayed/logged the same as php errors.) you would then remove any existing database error handling conditional logic in your code (for the connection and insert query), since it will no longer get execution upon an error. if you are familiar with the PDO extension, use it. it is much simpler and more modern than the mysqli extension, especially when dealing with prepared queries, which you should be using, since they provide protection against sql special characters in data values, for all data types, from breaking the sql query syntax. 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. your code generally follows this, but it has things like two session_start() statements, that needs to be cleaned up. the post method form processing should - detect if a post method form has been submitted before referencing any of the form data. keep the form data as a set in a php array variable, then operate on elements in this array variable throughout the rest of the code. trim all the input data, mainly so that you can detect if it consists of all white-space characters. validate inputs, storing validation errors in an array using the field name as the array index. after the end of the validation logic, if there are no errors, use the form data. after using the form data, if there are no errors, perform a redirect to the exact same url of the current page to cause a get request for that page. any redirect needs an exit/die statement after it to stop code execution. 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 display any errors and redisplay the form, populating the form field values with any existing data. since there won't be any existing data values the first time the form is displayed, you need to address this at the point of using the values in the form. php's null coalescing operator ?? is a good choice to use here. any external, dynamic, unknown value output in a html context should have htmlentities() applied to it to help prevent cross site scripting. here's a laundry list of addition things for the posted code - the php error related settings should be in the php.ini on your system use 'require' for things your code must have for it to work creating a sales order is an administrative activity. you should have a login and user permission system to control access to this operation don't copy variables to other variables for nothing, just use the original variables don't use multiple variables to indicate something when one will work, e.g. orderIDx/orderActivex the session can hold data from different parts of your application. don't completely destroy the session, only unset specific things when needed. since you will be directly testing/using the session variable, instead of copying them to other variables, you won't be destroying or unsetting session variables for the part of the code you have shown. don't blindly loop over external data. hackers can cause 1000's of post variables to be submitted to your code. instead, only operate on expected post entries. you should actually be using a data-driven design, where you have an array that defines the expected fields, their validation, and processing, that you would loop over to dynamically do this operation. don't use variable variables, especially on external data. this allows hackers to set ANY of your program variables to anything they want. don't redirect around on your site, accepting values in the url to control what gets displayed as the result of performing an operation. this opens your site to phishing attacks. if you have a need for using numerical values to indicate which of multiple states something is in, use defined constants with meaningful names, so that anyone reading the code can tell what the values mean in the validation code, setup a unique and helpful error message for each validation error for each input, i.e. don't make the user guess what was wrong with the submitted data if any of the fields/columns must be unique, define them as unique indexes in the database table, then test in the database exception error handling if the query produced a duplicative index error number (1062 if i remember correctly.) for all other error numbers, just re-throw the exception and let php handle it. an empty action="" attribute is actually not valid html5. to cause the form to submit to the same page, leave out the entire action attribute don't put name or id attributes into the markup unless they are used you should validate the resulting web pages at validator.w3.org <option tags don't have name attributes you can put php variables directly into over-all double-quoted strings, without all the extra concatenation dots and quotes. just about every SELECT query should have an ORDER BY ... term so that the rows in the result set are in a desired order don't echo static html. just drop out of php 'mode' when you build and output the <option lists, output the selected attribute for the option that matches the existing form data when you output the checkbox field, you would output the checked attribute if that field is set in the existing form data the point where you are using - echo '0 Results'; won't display anything because it is inside the <select></select> tags. if there are no option choices, you should probably not even output the markup for the entire field, and output the message instead when conditional logic 'failure' code is much shorter then the 'success' code, invert the condition being tested and put the 'failure' code first. this will make your code clearer and cleaner
  18. once the form has been submitted, except for unchecked checkbox/radio fields, all the fields will be set and they will be a string data type, regardless of what value they contain. empty always-set fields will be an empty string. unless you have code setting the values to null and are using those values in the sql query statement in such as way that the null value will get used as is, e.g. not quoted, or you are dynamically building the sql query statement and leaving the fields out, or are explicitly using the DEFAULT keyword for the value, nulls or the defined default value won't get used. you will need to post all the code we would needed, form and form processing, to reproduce the problem, along with your database table definition for anyone here to directly help.
  19. if you were doing this for real, where the price can change over time, the pricing would be stored in a related table, associated back to the token rows through the token's id, with a token_id, price, and effective start and effective end datetime columns. the point of the id column in this table is to assign a token id (auto-increment integer primary index), that would be stored in any related data table. this is the value that the form would submit for the selected token and would be stored in the usertoken table, not the token name. the balance is a derived value. you would not maintain the balance as a single value in a column, but would instead calculate it when needed. to do so, you need an account(ing) table, with a separate row inserted for each deposit/withdrawal that affects the account balance. also, the full name should be stored, using two columns, e.g. first_name, and last_name, so that you can uniquely distinguish between and search for people by name, e.g. is someone Ross Martian or Martian Ross? the account(ing) and usertoken table would use the id value from the users table, to related any stored data back to the correct user. this table should contain all the who, what, when, where, and why information about the purchase. the who would be the user_id of the buyer. the what would be the token_id, quantity, and purchase price (if you have a separate table for the pricing, you don't need this value). the when would be the datetime of the purchase. the where would only apply if there's a location associated with the purchase. the why would be a status/type value or memo field describing the reason for the purchase. this table doesn't need the account number, as that is defined in the users table and is known based on the user id. also, the totalbuy is a derived value that isn't stored. it is calculated when needed using the quantity and the purchase price (or the separately stored price at the datetime of the purchase.) the discount amount should be calculated and inserted as a separate row, in a related discount/interest accounting table, related back to the usertoken through the id in the usertoken table. you must do this as a single 'atomic' operation, in one query. the way to do this is use the query technique shown in this thread - https://forums.phpfreaks.com/topic/315532-avoid-appointment-conflict where you have an INSERT ... SELECT query that will only insert a new row in the usertoken table if the where clause calculates if the user's current balance - by summing the user's accounting rows, discount/interest rows, minus the user's existing token purchase amounts, is greater then or equal to the total amount of the submitted purchase. and just to clarify, the only two values submitted from the form should be the selected token id and the quantity. everything else should use values that only exist on the server.
  20. 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.
  21. 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.
  22. 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.
  23. 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.
  24. 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.
  25. 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.
×
×
  • 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.