Jump to content

mac_gyver

Staff Alumni
  • Posts

    5,341
  • Joined

  • Days Won

    173

Everything posted by mac_gyver

  1. so, how about the var_dump output? if you actually use all the points made, including switching to the much simpler and more modern PDO database extension, you will get code that looks like this (untested) - <?php // initialization session_start(); $errors = []; // array to hold user/validation errors // post method form processing if($_SERVER['REQUEST_METHOD'] === 'POST') { // validate input data if(!isset($_SESSION['id'])) { $errors['logged_in'] = 'You must be logged in to delete your bandstage data.'; } // if no errors, use the input data if(empty($errors)) { require 'pdo_connection.php'; $sql = "DELETE FROM bandstage WHERE id = ?"; $stmt = $pdo->prepare($sql); $stmt->execute([ $_SESSION['id'] ]); } // if no errors, success if(empty($errors)) { // note: if you want to display a one-time success message, store it in a session variable, then test, display, and clear that variable in the html document $_SESSION['success_message'] = 'You have successfully deleted your bandstage data.'; // redirect to the exact same url of the current page to cause a get request for the page - PRG Post, Redirect, Get. die(header("Refresh:0")); } } // get method business logic - get/produce data needed to display the page // html document // note: this in incomplete and only shows the parts corresponding to this example code ?> <?php // display and clear any success message if(isset($_SESSION['success_message'])) { echo $_SESSION['success_message']; unset($_SESSION['success_message']); } ?> <?php // display any errors if(!empty($errors)) { echo implode('<br>',$errors); } ?>
  2. using var_dump() on the session variable (see my reply above) will help identify if it contains any non-printing/white-space characters. if by that you mean the header() statement. no, he told you to put that line of code - at the header() statement, it is too late to put in that line of code. does that mean you have multiple databases or does that mean you actually have only one database, but it has multiple tables in it? if you do have multiple databases, are you selecting the correct one and is that the same one you are looking at to see if the records are being deleted?
  3. what result or output are you getting on this page? what does adding the following, after the session_start(), show - var_dump($_SESSION['id']); a bunch of points about the posted code - the php error related settings should be in the php.ini on your system. if you put the database connection code in a separate .php file, you can just require it when needed. this will save you from having to redact the connection credentials when posting the code. the line that barand posted, which enables exceptions for errors, should always be part of your code. this is also the default setting in php8+ don't output raw database connection onto a web page or tell the visitor that a database error occurred. this only helps hackers. when using exceptions for database statement errors, the error handling logic you have now won't ever be executed upon and error and should be removed, simplifying the code. you should set the character set when you make the database connection to match your database tables, so that no character conversion occurs over the connection. you should be using a post method form when performing an action on the server, such as deleting data. if this a get method button/link, when a search engine indexes your site, you could end up with a bunch of your data getting deleted. $_SESSION['id'] is an 'input' to your code. you must validate it before using it. technically, you should trim() it before validating it if it could have accidentally gotten modified when putting the value into the session variables. don't copy variables to other variables for nothing. just use the original variables. you should also be using a prepared query when supplying external, unknown, dynamic value to a query when it gets executed. php automatically destroys all resources on a page when your script ends. there's no need to close database connections in your code. upon successful completion of post method form processing code, you should perform a redirect to the exact same url of the page to cause a get request for that page. this will prevent the browser from trying to resubmit the form data should the user reload or navigate away from and back to that page.
  4. exactly what settings and what values did you set them to? you should set error_reporting = E_ALL (this value is case-sensitive) and set display_errors = On (this value is not case-sensitive) and these lines should not be commented out. did you stop and start your web server to insure that any changes to the php.ini took affect? what does the phpinfo() output show for these settings after you have attempted to set them and restarted the web server?
  5. i don't think anyone understands, based on the description, what the overall work flow is. could you describe or show what the user should see at each step. you state the html table should be empty while the page is loading, but you show php code looping over the result of some not-shown query producing that html table output. if the purpose of this php code is to produce a 'template', which the ajax success code is supposed to populate with values, you need to tell us? you would also not use a loop. you would only output one instance of the markup. the only thing i can tell you based on the posted attempt is what has been written in your threads before, you cannot repeat ids in the markup. all the code like - id="Ass_Description" will not work when there is more than one instance on a page. you need to use the technique from the last thread, where class names are used, then you use the .find() method to reference each element.
  6. https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
  7. the boolean value returned by the exaction of a SELECT query only indicates that the query executed without error (a true value) or failed due to a query error (a false value.) it doesn't indicate that the query match any data. a query that doesn't match any data is a successful query, but returns an empty result set. there's a single query that does what you want. an INSERT ... ON DUPLICATE KEY UPDATE ... query. you would define the uid column as a unique index if it is not already defined that way. there's no need to try to select data in order to decide if you should insert new data or update existing data and in fact, there's a race condition in the existing code where multiple concurrent instances of your script can all find that data doesn't exist and will all attempt to insert the same data, resulting in duplicates or in errors. also, use a prepared query when supplying external, unknown, dynamic values to a query when it gets executed. there's two reasons for doing this - 1) addslashes() doesn't protect against every possible character that can break the sql query syntax, since it doesn't take into account the characters set of your database tables, which is why php remove its ridiculous magic_quotes a long time ago, and 2) it will provide a performance increase when executing the same query more than once within one instance of your script.
  8. this code can be greatly simplified, because writing out code for every input or combination of values is not effective programming. switching to the much simpler and more modern PDO database extension will eliminate about half of the database statements. this alone will answer your database questions since the PDO extension was designed to be simple and usable. here's a specific list of practices, most of which will simplify and clean up the code - put the php error settings in the php.ini on your system, so that you can set/change them at a single point. you cannot set display_startup_errors in your code because php has already started when your code is being executed. the code for any page should be laid out in this general order - 1) initialization, 2) post method form processing, 3) get method business logic - get/produce data needed to display the page, 4) html document. most of the php code needed for searching/pagination goes in the get method business logic section. post method forms are used when performing an action on the server, such as inserting, updating, deleting data, sending an email, writing/updating a field. get method forms/links are used when determining what will be displayed on a page, e.g. searching, pagination. the second entry in the $tbls array contains a $. did you actually use this array to validate the $tbl input? don't use the root database user in applications. create a specific database user, with a password, with only the necessary permissions for use in an application. don't output raw database errors onto a wab page. this only helps hackers. instead, use exceptions for database statement errors (this is the default for both the mysqli and PDO extension in php8+) and in most cases simply let php catch and handle any database statement error, 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 exception to this rule is when inserting/updating duplicate or out of range user submitted data. in this case, your code would catch the exception, test if the error number is for something your code is designed to handle, and setup a unique and helpful error message for the user. for all other error numbers, just re-throw the exception and let php handle it. this will let you remove all the existing database error handling logic, simplifying the code. btw - mysqli_stmt_execut() can fail with an error but you don't have error handling logic for it, but since you will be removing all the existing error handling logic when using exceptions for database statement errors, you won't have to remove this non-existent code. if you are going to continue to use the mysqli extension, don't use mysqli_stmt_init() followed by mysqli_stmt_prepare(), just use mysqli_prepare(). if you are going to continue to use the mysqli extension, use the OOP notation. it is both simpler and because the php error response is different between the procedural and OOP notation, things that are fatal problems will produce fatal php errors when using OOP, but only produce warnings when using procedural notation. in most cases, you don't need to free prepared statements, result sets, or close database connections since php will destroy all resources created on a page when your script ends. you should keep the input data as a set in a php array variable, then operate on elements in this array variable throughout the rest of the code, i.e. don't write out line after line of code that's basically copying each input to another variable. you should trim all input data before validating it. after you do the above item, you can accomplish this with one single line of php code. related to the above item, don't copy fetched data to other variables for nothing. just use the original variables that the data is in. you should store user/validation errors in an array, using the field/input name as the main array index. after the end of all the validation logic, if there are no errors (the array holding the errors will be empty), use the submitted data. if there are errors, the code will continue on to display the html document, test and display any errors, re-display any form, populating the form field values with any existing data so that the user doesn't need to keep reentering/selecting data over and over. any dynamic value you output in a html context needs to have htmlentities() applied to it to help prevent cross site scripting. at the point of dynamically building the sql query statement, the table and columns names can technically be anything and should be enclosed by back-ticks so as to not produce sql errors. are you sure you actually tested this? the definition for $links_table_columns doesn't exist in the code and even if it did, it is apparently permitted column names, so the error message would be for an invalid column, not an invalid table. pagination involves two similar queries. the first query is to get the total number of matching rows. the second query is to get the logical page of data. the common part of both of these queries should be built once, in a php variable, with a corresponding array of input parameters. the common part of the query is from the FROM term ... through to any HAVING term. the query to get the total number of matching rows should use SELECT COUNT(*) followed by the common part of the query, i.e. it should NOT select all the data just to get a count of the number of rows of data. the data retrieval query would instead SELECT the columns you want, followed by the common part of the sql query, followed by an ORDER BY term, and then the LIMIT term. you should supply the two LIMIT values via prepared query place holders and add (append/merge) the two values to the array of input values. since you will be using a SELECT COUNT(*) ... query to get the total number of matching rows, you won't need to deal with mysqli's mysqli_stmt_store_result() and mysqli_stmt_num_rows() don't use a series of name_x variables. use an array. arrays are for sets of data where you will operate on each member in the set in the same/similar way. you can then use php's array functions to operate on the arrays of data. the pagination link markup should be built in a php variable so that you can output the result wherever and however many times you want. use relative urls in the pagination links. this will eliminate PHP_SELF. to build the query string part of the pagination links, get an existing copy of any $_GET parameters (this will automatically include any table, input, col, bool, and limit values so that you don't need to write out code for each one) set/modify the page (pg) element, then use http_build_query() to build the query string. this will take care of urlencodeing the values.
  9. what symptom or error are you getting that leads you to believe that? btw - the only redirect you should have in your post method form processing code should be to the exact same url of the form processing code to cause a get request for that page. this will prevent the browser from trying to resubmit the form data should the user reload the page or navigate away from and back to that page, which will let someone use the developer console network tab to see what the username and password is. if you want the user to be able to go to some other page, provide navigation links.
  10. first of all, don't bother with the mysqli extension. it is overly complicated and inconsistent, especially when dealing with prepared queries, which you need to use to prevent any sql special characters in a value from being able to break the sql query syntax, which is how sql injection is accomplished. instead, use the much simpler and more modern PDO extension. here's a list a do's and don'ts for the posted code - you need to use a prepared query when supplying any external, unknown, dynamic values to a query when it gets executed. this will require that you change any place there's an $sql input parameter to also include an array of input values, such as what would be present in a WHERE ... clause. you would also supply the offset and rows_per_page in the LIMIT term via prepared query place-holders and append the values to the array of input values. don't SELECT all the rows of data to get the total number of rows. instead, use a SELECT COUNT(*) ... query, then fetch the COUNT(*) value. the common part of the sql query, from the FROM ... term though to any HAVING ... term needs to be used for both the SELECT COUNT(*) ... and the data retrieval query. this is the value you should build in the $sql input parameter. just about every SELECT query that returns more than one row should have an ORDER BY ... term so that the rows of data are in a desired order. don't use PHP_SELF and all the related code/values. you can use relative urls in the links. when you build the pagination links, start with a copy of any existing $_GET parameters, set/modify the page parameter, then use http_build_query to build the query string part of the links. this will eliminate the need for the $append value. use exceptions for database statement errors (this is the default error mode for both the PDO and mysqli extensions in php8+) and in most cases simply let php catch and handle any database 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 eliminate the need for the existing error handling and debugging logic. don't use the @ error suppressor, ever. there's no need. when learning, developing, and debugging code/query(ies), you should display all php errors. when running code on a live/public server, you should log all php errors. there's no need for the pagination code to test for a valid database connection. if the database connection fails, the page shouldn't ever get to the point of trying to use the connection for anything. the code for any page should be laid out in this general order - 1) initialization, 2) post method form processing, 3) get method business logic - get/produce data needed to display the page, 4) html document. the code to get the logical page of data and build the pagination links should be located in item #3 in this layout. OOP is NOT about wrapping a class definition around your main code and adding $this-> in front of everything to make it work. for example, the offset value is only used in one place. there's no need for it to be a class property. just use a regular/local variable for the value.
  11. a <button> by itself doesn't do anything. a button with type='submit' must be part of a form. a button without type='submit' must have an event or javascript associated with it to do anything. you will need to put a complete post method form, with a button with type='submit', within the html table cell, for this to work.
  12. conditional statements exist in programming languages so that you can write code that makes decisions when it runs, such as only outputting markup when there's data to display. the existing code has a conditional test in it to only output the markup inside the tbody if there is data to display. wouldn't the answer to your question be to move the start of that conditional test so that it only outputs the table/thead markup when there is data to display?
  13. ^^^ this part of the code gets the selected brand id and calls the ajax code. why did you change this part of the code? the part you need to change is the code that uses the result of the ajax call.
  14. if you read the information that I posted, you will know why this doesn't work. you CANNOT repeat ids in the markup. you must use some other way of referencing the elements. i showed code to do this by finding the .closest parent container, then .finding an element with a class name within the parent container. the reason no one is posting fixed code is because you would not learn anything by just repeating what you see. programming is a writing and reading activity. you must actually understand the meaning of the words and syntax you are using. copy/pasting something that someone else writes doesn't do this.
  15. your browser's developer tools console tab may contain errors that would help you find the problem. the OP only half did the first item i listed (added a class, rather than changing the id to a class), leaving duplicate ids in the dynamically added fields. the second item i listed was done. all the rest of the information i listed was ignored.
  16. there are two reason this is not working - 1) ids must be unique. you cannot use id="Brand" more than once on a page, and 2) the dynamically added elements don't exist when you are attaching the on change event handler (even if you change the selector to be a class name.) you must attach the on change event handler to an element that exists at the time (document is the easiest, though not the most efficient), that will contain the elements you want the event handler to fire for. assuming you change id='Brand' to class='Brand', the following will attach the on change event handler to all instances of the <select class="Brand" ... within the html document - $(document).on('change', '.Brand', function(){ since ids must be unique, all the rest of the code manipulating the DOM must be changed so that they don't rely on ids. the way to do this is give the <tr a class name that you can search for, such as 'parent-container', you can then find the current parent container using - var parent = $(this).closest('.parent-container'); you can then find and reference the elements within the parent container, by a class name, such as - parent.find('.Category').html(html);
  17. your web hosting probably has a Frequently Ask Question section that lists any requirements and a code example to send emails. you would need to post any code you have tried to get any help with what could be wrong with it. code examples you find on the web as usually lacking in security, lacking a good user experience, are filled with unnecessary typing, are missing error handling and validation logic that would get them to tell you (display/log) why they aren't working, and most, incorrectly, are using the email address that was entered by the visitor as the From: email address (these emails are NOT being sent from the email address that was entered, they are being sent from the mail server at your web hosting and the Form: email address must use a domain name that is either at your web hosting or is tracible back to the ip address of the sending mail server through dns records.)
  18. if you index/pivot the data using the question as the main array index, you can directly produce the output using two nested foreach() loops, without needing extra variables and conditional logic to keep track of where each group of data changes or to output the starting/ending markup for each section, since there will be specific single points in the code for the start and end of each question section and of each option section. PDO even has a fetch mode to do this - PDO::FETCH_GROUP, which will index/pivot the data by the first column being SELECTed. to do this, change the fetchAll() line to this - $questions = $statement->fetchAll(PDO::FETCH_GROUP); you can then produce the output using this logic - foreach($questions as $question=>$group) { // start of question section echo $question; // loop over the rows in the 'group' to display the choices foreach($group as $row) { // start of choice section echo $row["choice"]; // end of choice section } // end of question section } to apply the answerA, answerB, ... classes to each choice section, you would store them in an array, e.g. $choice_styles = ['answerA', 'answerB', 'answerC', 'answerD'];, and change the second foreach loop to - foreach($group as $index=>$row) you can then get the correct style name in the choice section using - $choice_styles[$index].
  19. you must tell us what result you did get, even if the result was a blank page, and tell us what result you expected. your data is not normalized, making every query and operation on the data harder. you should have a brand table, with id (auto-increment primary index) and name columns. this will establish brand_id values. you would store the brand_id in any related table, such as the model table. would then simply query the brand table to get a list of the brand names and their ids for the select/option menu.
  20. the query and related code already is using the MySQL database. what makes you think it is not?
  21. it doesn't look like you are reading, understanding, or using the information from the previous threads. your post method form processing should - detect if the post method form was submitted (it is actually doing this.) trim the input data, one time, then use the trimmed data throughout the rest of the code. validate the trimmed data. after the end of the validation logic, if there are no errors, use the summitted data. your current test - if ($username == true && $password == true) { doesn't do this. the $username and $password will be true values, even if they contain invalid characters. one of the points of remembering if there are any errors, by storing them in variable(s), is so that you can test if there are or are not any errors in your code. in your previous thread, i recommend using an array to hold the user/validation errors. if you do this, you can simply test if the array is empty() to determine if there are no validation errors. the registration form and processing code should be very similar to the login in form and processing code. the major differences are - 1) in the login processing, after trimming the data, you don't really care what characters the values contain, all you care about is if the username/password matches an entry in the data file and 2) the actual processing of the validated data is different. why do you have a bunch of different variable name between the two pieces of code? you even have a nonexistent $name variable in the username form value='...' attribute that should be producing a php error. why are you using file() in the registration code and file_get_contents() in the login code? your logic in this code is unconditionally testing if the passwords match, without testing if the username was found. as to this ridiculous test_input() function that you found on the web. the only thing it is doing that is correct is trimming the data. the function is improperly named (it's not testing anything), it should not unconditionally apply stripslashes (when this was necessary to do, it needed to be conditionally applied, but the need to do this has been removed from php for a long time), and htmlspecialchars is an OUTPUT function, do NOT apply it to the input data in your form processing code.
  22. here's a list of suggestions for the code implementation - use a variable (or defined constant) for the file name so that if you need to change it, you can do so in a single location. if you were doing this for real, you would need to use file locking to insure that you don't corrupt/truncate the data file when there are multiple concurrent instances of your script trying to access the file. your code should test if the file exists before attempting to read it, in order to prevent php errors when the file initially doesn't exist. you should also test the result of the file() call in case the file does exist but it is empty. after you you read the data from the file, when you explode the data you should store it into an array, indexing it using the lowercase username. this will let you simply test if the lowercase submitted username exists in the data by using an isset() statement. by using the lowercase of the usernames from the data file and the lowercase of the submitted username, you will enforce uniqueness, e.g. MyUserName and myusername will be treated as the same value. the username that you store in the data file, and that you display, should retain the letter-case that was originally entered. to get a form to submit to the same page it is on, leave out the entire action='...' attribute. there's no need to use $_SERVER['PHP_SELF'] in this case and if you ever do need to use $_SERVER['PHP_SELF'], you need to apply htmlentities() to it to help prevent cross site scripting. if you put the closing </label> tag after the form field it goes with, you can leave out the for='...' and corresponding id='...' attributes (which you are currently missing most of.)
  23. your code is not testing the same value for each field throughout the code, because you are trimming it in one place, but using the original value in other places. your post method form processing code should - not try to detect if the submit button isset(). instead, test if a post method form was submitted. don't create discrete variables for each form field and don't copy variables to other variables for nothing. instead, keep the form data as a set in a php array variable, then use elements in this array variable throughout the rest of the code. don't create separate variables for each error. instead, use an array for the user/validation errors. when you add errors to the array, use the field name as the array index. this will let you perform dependent validation tests on a field only when there are no previous validation errors and it will let you output the errors adjacent to the corresponding field if you desire. trim all the input data at once, then use the trimmed data throughout the rest of the code. after you do item #2 in this list, you can trim all the data using one single line of code. after the end of the validation logic, if there are no errors (the array holding the user/validation errors will be empty), use the form data. after the end of 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 that 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. by passing the success message through the url in the redirect, you are opening your site to phishing attacks and cross site scripting. every redirect needs an exit/die statement to stop php code execution. a header() statement doesn't stop php code execution. if there are user/validation errors at step #5 or #6, the code will continue on to display the html document, display the errors, re-display the form, populating the field values with any existing data. any data you output in a html context should have htmlentities() applied to it to help prevent cross site scripting.
  24. assuming that uploads are enabled on the server (which you can test using code) and you have a valid post method form, with at least one type='file' field, if the $_SERVER['REQUEST_METHOD'] === 'POST' and both the $_POST and $_FILES arrays are empty, it is likely that the post_max_size was exceeded. you can use this as the condition to setup and display a message that the total size of the post data was too large. the Content-Length is available in $_SERVER['CONTENT_LENGTH'] (which is in bytes.) if it is set, this is the value that the web server compares with the post_max_size value to attempt to abort requests that are too large. both the upload_max_filesize and post_max_size can be either in bytes or K/k, M/m, or G/g abbreviations, therefore you must convert these to the same units in order to compare them. your post method form processing should - detect if a post method from was submitted detect if there is $_POST/$_FILES data. test the $_FILES[...]['error'] element validate the uploaded file information i recommend that you use an array to hold user/validation errors. after the end of all the validation logic, if the array is empty, there were no errors and you can use the submitted form data. the ['type'] element comes from the request, can be set to anything, and cannot be trusted. you should determine the mime type on the server. based on the use of the back-button history for navigation, your form and form processing code are on different pages. these should be on the same page in order to simplify the code, make it easier to secure the code, and provide a better user experience.
  25. you are getting a fatal error in the browser. you need to use your browser's develop tools console tab to debug what is going on in the browser. the element you have given id="selectYear" to, is the button, not the select menu. as to the $cusid. this is already known on the server when the main page was requested. why are you passing it through the form? external data submitted to your site must always be validated before using it. if you use the already validated value that you already know on the server, you can simplify the 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.