-
Posts
5,450 -
Joined
-
Days Won
175
Everything posted by mac_gyver
-
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].
-
Create dropdown list from database on dynamically added row
mac_gyver replied to Senthilkumar's topic in PHP Coding Help
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. -
Filter the data table based on the User Login
mac_gyver replied to Senthilkumar's topic in MySQL Help
the query and related code already is using the MySQL database. what makes you think it is not? -
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.
-
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.)
-
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.
-
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.
-
Using PHP and Ajax to show ORDERS by Year without refreshing page
mac_gyver replied to JunWei's topic in PHP Coding Help
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. -
sorry for how this sounds, but this code is programming nonsense. the biggest problem with it is that OOP is not about wrapping class definitions around main application code, then needing to add $var-> in front of everything to get it to work. all this is doing is creating a wall of unnecessary typing, that's changing one defining and calling syntax for another more verbose one. additional problems with this code is that it is insecure in may places, it is applying htmlspecialchars and strip_tags improperly to input data, it has no validation or error handling logic, it is using a prepared query for queries that don't have any external data being used, it is not properly using a prepared query that have external data being used, it is repetitive, and it's class methods/functions don't accept input data as call-time parameters (requiring even more $var->property statements to make it work.) the only correct programming practices it contains are - it is using dependency injection to make a single database connection available to the classes that need it and it is using a COUNT() query in a few places to get counts of matching data. don't waste any time on using this code, either as a learning resource or as a way of achieving a discussion forum.
- 1 reply
-
- 1
-
How do I get php contact forms working on Godaddy?
mac_gyver replied to DeclineoftheWest's topic in PHP Coding Help
data ($_POST, $_GET, $_COOKIE, $_FILES, and some $_SERVER variables) submitted to any site can come from anywhere, not just your forms/links/cookies, can be set to anything, and cannot be trusted. you should trim all external data, mainly so that you can detect if it is all white-space characters, validate it, then use it securely in whatever context it is being use as. in a html context, such as an email body or a web page, you should apply htmlentities() to any external, unknown, dynamic values to help prevent cross site scripting. for a value that has a specific format, like an email address, after you have validated that it is not an empty string, you should validate that it is a properly formatted email address. for something like a contact form, where you don't have the ability to limit its use to only known, logged in users, yes, you should use a captcha. your post method form processing code should - if the form and form processing code are not on the same page, they should be. this will allow you to display any validation errors and repopulate the form field values upon a validation error. detect if a post method form has been submitted. this will insure that if the page is ever requested via a get request, that it won't waste time running code when there is no post data to use. keep the form data as a set in an array variable, then use elements in this array variable throughout the rest of the code, i.e. don't write out lines of code copying variables to other variables for nothing. after you do item #3 on this list, you can trim all the data at once using one single line of code. don't unconditionally loop over the $_POST data. hackers can submit 100's of post variables to your code. you should instead define an array of expected fields, then loop over this defining array when validating and using the submitted data. you should not directly accept the subject from external data. if there's a need for different subject values, define them in an array, with a numerical id indexes, then get the actual subject from the submitted numerical id value. you should have error handling logic for the mail() call. if it returns a false value, the email was not accepted by the sending email server. you would setup a general failure message for the user, and you would log everything about the attempted email so that you will both know that it failed and can perhaps see a pattern as to why it may have failed. you would only display the success content if the mail() call returned a true value. after successfully using the submitted form data, with no errors, you should perform a redirect to the exact same url of the current page to cause a get request for that page. this will prevent the browser from resubmitting the form data if the user reloads that page or navigates away from and back to that 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. don't echo static markup. there's no php code in that success message. just drop our of 'php' mode and put the markup in-line in the file. -
How do I get php contact forms working on Godaddy?
mac_gyver replied to DeclineoftheWest's topic in PHP Coding Help
except during testing, when you enter your own email address, these emails are NOT being set From the name/email address that is entered in the form. they are being sent from the mail server at the web hosting. the domain in the From email address must either directly correspond to the sending mail server or there must be dns zone records (specifically an SPF record) at the domain in the From email address that indicates your email server can send email for that domain. short-version, use a From email address that exists at the web hosting. -
Potential Issue - Returning Too many results
mac_gyver replied to CodeRed-Alpha's topic in PHP Coding Help
there's so much wrong with just this small section of code - it is using a post method form for determining which record to edit. this should use a get method form/link, so that if the user wants to return to the same point, they can bookmark the url or if there's a problem they can submit the url so that someone else can view and see the problem. the only time you should edit/update data is when correcting a mistake in a value or just changing a status value, not when performing normal data operations. for normal data operations, you should insert a new row in an appropriately defined table for every separate operation, so that you have an audit/history trail, that would let you detect if a programming mistake, accidental key press, or nefarious activity caused data to be entered and also so that you can produce a history report. the use of sprintf() provides no security against sql special characters in a value from being able to break the sql query syntax, which is how sql injection is accomplished. the simplest, fool-proof way, to provide security in an sql context, for all data types, is to use a prepared query. since the mysqli extension is overly complicated and inconsistent, especially when dealing with prepared queries, this would be a good time to switch to the much simpler and more modern PDO extension. the database should enforce uniqueness, by defining any column must not contain duplicate values as a unique index. this will produce a duplicate index error when attempting to insert/update duplicate values, that the error handling would detect and report back to the user that the value they tried to insert/update already exists. the code should not use a loop to fetch data from a query that is expected to match at most one row of data. based on the columns oil_due, inspect_date in a table named Trucks, the database is not designed correctly. There should be a table where the one-time/unique information about each vehicle is stored. this table will define a vehicle id (autoincrement primary index) that gets used when storing any related data. service records would then be stored in a separate table, one row per service, using the vehicle id to relate them back to the vehicle they belong to. if there are multiple primary defining records for any vehicle, these should be found and consolidated into a single record, the columns that must be unique need to be defined as unique indexes, and the error handling for any insert/update query need to be changed to detect a unique index error number and report to the user that the data already exists. if this Trucks table is actually the table holding the service records, there need to be a row per service operation per vehicle. the code would then query for any records that have a pending/open status value. when a service is performed, the status for that record would be updated to a value indicating it is 'complete' and what datetime it was completed. any future scheduled service would be inserted as a new row with a pending/open status value. -
the error means that $login_level is a boolean (true or false) value, but the code expects it to be an array with a group_status element. either something has changed to cause the find_by_groupLevel() function to return an unexpected value OR that part of the code (which is using an exact comparison with a string consisting of '0') never actually worked, wasn't fully tested, and was probably always producing this error, but the error wasn't being reported/displayed. what is the code for the find_by_groupLevel() function and what is the expected value it should return for both a non-banned and a banned user?
-
Selecting a specific user from drop down in php Mysql
mac_gyver replied to PNewCode's topic in PHP Coding Help
if you are asking how to make the selected option 'sticky', you would output the selected attribute for the option choice that matches any existing gname input value. if you are asking how to narrow down the choices, this is called autocomplete/typeahead and uses javascript and ajax requests to populate a dropdown list with entries from your database that match the portion of text that has been typed in a text input field. you can then just click on the choice you want to complete the entry in the field. there are countless example scripts posted on the web. -
the uploaded file is at the path/name given by the ['tmp_name'] element. you must also test if the file upload was successful before referencing any of the uploaded file information. if the total size of the post form data exceeds the post_max_size setting, both the $_POST and $_FILES arrays will be empty. after you detect if a post method form was submitted, you must test for this condition. after you have detected that there is data in $_FILES, you must test the ['error'] element to make sure the file was uploaded without an error. ref: https://www.php.net/manual/en/features.file-upload.php for the $_POST field data, use the $_POST array, not the $_REQUEST array. don't copy variables to variables for nothing, this is just a waste of typing. if you have more than about two form fields, you should use a data-driven design, and dynamically validate and process the form data. except maybe during testing, when you are entering your own email address at your web hosting in the form, these emails are not being sent from the email address that someone enters in the form. they are being sent from the mail server at your web hosting and the from email address must either directly correspond to the sending mail server or you must set the dns zone records at the sending mail server to indicate it is allowed to send email for the domain in the from email address.
-
that would be exactly the information found in the php documentation - https://www.php.net/manual/en/book.pdo.php specifically for Prepare() and Execute() - https://www.php.net/manual/en/pdo.prepare.php and https://www.php.net/manual/en/pdostatement.execute.php
-
the points that have been made have INCLUDED the reason why you should do these things. these points have been to make your code - secure (it currently is not), provide a good user experience, simplify (i and others have used a form of the word simple in several of the replies) the code (what you have shown contains a lot of unnecessary and unused code, variables, and queries), reduce resources and speed up the code (making a database connection is one of the most time consuming operations you can do on a page, which is why you should make only one per page), and through having useful error handling and validation logic, help get your code/query(ies) to either work or get them to tell you why they won't. the reason we are trying to get you to simplify the code is because you MUST go though all this code at least once to update it. if you can eliminate the unnecessary code, variables, and queries, you will have less things that must be updated. if you really have hundreds of pages of bespoke code like what you have shown so far, it may be a better use of your time learning and using a general-purpose data driven design, so that you can get the computer to do the work for you, rather than you spending hours upon hours writing and trying to maintain code on so many web pages.
-
if you make use of the suggestions given in this thread for the LogMeX2 function code, you should end up with this simple, and secure code (untested) - // verify the user log in credentials // return user id if a match, else return false function LogMeX2($pdo,$username,$password) { $sql = "SELECT User, UserKey FROM LIBusersX WHERE UserN = ?"; $stmt = $pdo->prepare($sql); $stmt->execute([$username]); // fetch/test if a row was found, i.e. the username was found if(!$row = $stmt->fetch()) { // username not found return false; } // username found, test password if(!password_verify($password,$row['UserKey'])) { // passwrod didn't match return false; } // username and password matched, return user id return $row['User']; }
-
nothing has changed about or die() being supported. it was always a bad practice to use for error handling and since the PDO extension uses exceptions for errors for all (default in php8+) the statements that interact with the database server - connection, query, prepare, execute, and exec, you were told the or die() logic will never be executed upon an error and should be removed. the great thing about using exceptions for errors is that your main in-line code only 'sees' error free execution, since execution transfers to the nearest correct type of exception handler upon an error or to php if there is no exception handling in your code. if execution continues to the line right after you have executed a query, you know that there was no error, without needing any conditional logic, simplifying the code. the posted logic makes no sense. you are running a SELECT query to get a count of the number of rows, to decide to run the SELECT query again. just run the second SELECT query and fetch the data from it. if the query matched a row, the fetched data will be a boolean true value. if the query didn't match a row, the fetched data will be a boolen false value. you were also told elsewhere that magic_quotes, which provided some security for string data values, has also been removed from php and that you need to use a prepared query when using external, unknown, dynamic data with a query. converting any query to a prepared query is extremely simple - remove the variables that are inside the sql query statement (keep these variables for use later). remove any single-quotes that were around the variables and any {} or concatenation dots that were used to get the variables into the sql query statement. put a prepared query place-holder ? into the sql query statement where each variable was at. call the ->prepare() method for the resulting sql query statement. this returns a PDOstatement object, and should be named $stmt or similar. call the ->execute([...]) method with an array containing the variables you removed in step #1. for a SELECT query, use either the ->fetch() method (for a single row of data), the ->fetchAll() method (for a set of data), or sometimes the ->fetchColumn() method (when you want a single value from one row of data.) lastly, md5() was never intended for password hashing. you should be using php's password_hash() and password_verify() for passwords. also, why are you hashing names/usernames? this prevents any wild-card searching or sorting.
-
you have stated you have a lot of code that needs to be converted. a GOOD reason to name the variable as to the type of connection it holds, e.g. $pdo, is so that you can tell by looking/searching which code has been converted and which code hasn't, then after it has been converted, anyone looking at the code can tell which database extension it is using (parts of the mysqli extension look exactly like the PDO extension.)
-
the OP is attempting to learn, develop, and debug code/query(ies) on a live/public server. either the last posted code wasn't successfully getting uploaded to the server or a lot of cheap web hosting set disk caching (time) to a high value to get as many accounts onto one server as possible and it was taking some time for the changes to take effect. you should be learning, developing, and debugging your code/query(ies) on a localhost development system and only putting your code onto a live/public server when it is mostly completed.
-
when you make the connection, you should set the error mode to exceptions, which is what you are doing, set emulated prepared queries to false, you need to add this, and set the default fetch mode to assoc, you are setting it to obj, which is not what you are using in the example code and is probably not what your existing code is using with the fetched data, which will require you to make even more changes to your existing code.
-
the php documentation lists the major changes going between each version - https://www.php.net/manual/en/appendices.php if there's not a huge amount of code, you could just post the entire project somewhere (github) and someone can review and list what things in it will need to be changed. agree with @benanamen, you should be updating to the latest php version, not php7.