Jump to content

mac_gyver

Staff Alumni
  • Content Count

    4,222
  • Joined

  • Last visited

  • Days Won

    106

Everything posted by mac_gyver

  1. mac_gyver

    How to short hand this

    $values and $periods are already arrays. do the same for $ItemsAnnual and make it an array and populate its values using a loop.
  2. mac_gyver

    upgrade to PHP 5.5, Site Doesn't work

    it would help to know what the old php version was. just an update to 5.5 (which should have or soon will be an update to 7+) doesn't break the mysql_ functions. it's more likely that the code is dependent on register_globals in order to function. if so, it will take rewriting all the code to use the actual php super global variables where the external $_GET, $_POST, $_FILES, $_COOKIE, and some $_SERVER variables are at. you would also want to update the code to use one of the current database extensions, and since query security also went away in php 5.4, in order to keep from having to add a bunch of code, it is better to switch to use prepared queries, with the php PDO extension, and to use exceptions to handle database statement errors. doing this will result in the simplest php code and simplest sql query syntax, which will reduce the amount of things you have to update, i.e. you can just eliminate a bunch of stuff, rather than to spend time on updating it.
  3. mac_gyver

    5K - Race

    when looping to produce that html table, you would actually loop from 1 to 14 and test if the corresponding $_POST['runner'] element is set, since there won't initially be any $_POST data.
  4. mac_gyver

    5K - Race

    some suggestions - 1) don't create a bunch of variables without a good reason. the original $_POST variable(s) the data is in are perfectly fine to use in the rest of the code. 2) use arrays for sets of data. the form field name should be an array, i.e. name='runner[x]' with the array index (x) value being 1-14. this will let you loop over the submitted data using a simple foreach(){} loop so that you can dynamically process the data. this will eliminate the temptation to write out 14 lines of code that are doing nothing useful, but to waste your time typing (unless this is part of a keyboard/typing class?) 3) leading zero's on numbers in php cause them to be treated as octal. either treat all the values as integers and zero fill them when displaying them, or treat all the values as strings. 4) the three separate arrays of registration values should be instead one array (use the same base array name for all three), with an index value that indicates the division (the index can either just be a number or a string, but needs to be in the order that you want to produce the output in.) 5) to produce the final output, loop over the array of submitted $_POST['runner'] data. this will give you the runner number for positions 1-14. at the point that you have the current runner number for a position, loop over the registration main array and use in_array() to find if the current runner number is in each successive registration sub-array. if the current runner number is not in the current registration sub-array, output a   in the current html table cell. if the current runner number is in the current registration sub-array, output the runner number in the current html table cell and increment a counter for the current registration sub-array index (use an array for the counter, with the index being the same index value you used in the registration main array.) to produce the last count row in the html table, just loop over the registration main array one more time and access the corresponding entry in the counter array. 6) you would want to make the form fields 'sticky' and set the value to any corresponding submitted $_POST['runner'] value, since you aren't actually storing the results in a database to make them persistent. 7) you would dynamically produce the form fields, rather than to have them statically written out.
  5. mac_gyver

    What is wrong with this line?

    1.b) additionally, one = is an assignment operator. two == is a comparison operator.
  6. mac_gyver

    What is wrong with this line?

    in order to put an array variable inside a string, it needs to be enclosed by {} however, there are a few things wrong with what that line of code is trying to do - 1) the mysqli_query() statement doesn't return data, it returns a result object, so, a variable holding the submitted password will never be equal to the value returned in that line. you would need to fetch the data first. 2) you should NOT store plain-text passwords. you need to use php's password_hash() and password_verify(). you would need to fetch the stored password hash and use password_verify() to test if the submitted password matches the hash. 3) you should NOT put external/unknown data directly into an sql query statement (and for those cases where it is safe to do so, string data must be enclosed by single-quotes.) you instead need to use a prepared query, with a ? place-holder in the sql query statement for each data value, then supply the data when the query gets executed. unfortunately, the php mysqli extension is overly complicated and inconsistent when dealing with prepared queries and you need to switch to the much simpler php PDO extension. doing this will actually simplify the sql query statement since the place-holder being put into the sql query statement eliminates the php variable, any {} around the variable, any single-quotes around the variable, and any concatenation dots.
  7. mac_gyver

    PHP Calendar with data from MYSQL

    someone already posted the steps you would perform -
  8. mac_gyver

    PHP Calendar with data from MYSQL

    before the start of the display code, you would query for and retrieve any event data matching the year and month being displayed. when you retrieve the data, you would store it as a sub-array of rows (there can be multiple events on any date) in a main array variable with the date (YYYY-MM-DD) value as the the main array's index. in your calendar display code, you would build the date (YYYY-MM-DD) value for the current day being displayed and test if the main array of retrieved data has an index for that date (you can just use isset().) if so, you would loop over the sub-array of data to reference each row of event information for that date.
  9. mac_gyver

    how to select two tables in update query

    as to displaying/logging the database statement errors. use exceptions to handle all database statement errors (connection, query, prepare, and execute) and in most cases let php catch the exception where it will use its error_reporting, display_errors, and log errors_settings to control what happens with the actual error information. the exception to this rule is if your application needs to detect and handle duplicate values for an insert/update query. your code would catch the exception in this case, detect if the error was for a duplicate index, set up and output an error message to the user telling them what is wrong with the data they submitted, or if error is not for a duplicate index, re-throw the exception and let php handle it. when learning, developing, and debugging code/queries, you would display all errors, which now includes the database statement errors, and when on a live/public server, you would log all errors, just by changing the php display_errors and log_errors settings. this will allow you to remove the existing error handling logic in your code, thereby simplifying it. to enable exceptions for the php mysqli extension, add the following line of code before the point where you are making the database connection - mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); lastly, since you need to change to use prepared queries when supplying external/unknown values to the sql query statement, you need to switch to the much simpler php PDO extension for all the database statements. the amount of code you have to write to accomplish a prepared query using the mysqli extension is an error prone waste of time (and the code needed to write a mysqli general purpose prepared query function/method is complicated and slow.)
  10. mac_gyver

    how to select two tables in update query

    you are going about this in the hardest way possible. even the naming of your tables and columns is not helping. your address table appears to be a rental unit table. it should be named that - rental_units. the id column in this table defines the unit id, the other column in that table is apparently the unit name. it should be named so - name. i'm assuming it is a varchar column because rental unit names can include alphabetic characters, A, B, C...? the amount table is some sort of unit dues payment table. it should be named to indicate the meaning of the data in the table - due_payments or similar name. the id column in this table defines the payment id, not the unit id. this table should have a separate unit_id column to relate the payment record back to the unit it corresponds to. the form to insert a new payment record should have a way of selecting from the existing units, such as a select/option menu. this will reduce typo mistakes and only allow valid units to be chosen. this select/option menu would display the unit name, but the value that is submitted would be the unit_id. the INSERT form processing code would insert a record into the payment table with the submitted unit_id, amount, and other fields you have defined. if you are editing an existing payment record, such as when correcting a typo in a value, you would reference the specific record using its payment id, not the unit_id. to display the corresponding unit name as part of this process, the SELECT query that retrieves the existing payment record would JOIN with the units table to get the unit name. the UPDATE form processing code would update the record indicated by the payment id value.
  11. if you are asking this question because your 1st code doesn't do what you expect, it's most likely because you are using one = in a comparison statement (which is a first week mistake) instead of two ==. despite what the documentation states, you can call bind result at any time after the mysqli statement object exists, but before you call the fetch statement (tested some time ago.) so, rather than to ask about which of the two versions of code is correct (neither will work correctly due to the above problem in both and the calling order of the bind result/fetch statement in the second one), come right out and state what sort of problem or error you are having that leads you to ask the question in the first place. at the risk of wasting time typing a reply that will be ignored again, you should NOT mix error handling logic with application functional logic. you should not combine both of these tests in this line of code - if(mysqli_stmt_execute($stmt)) && mysqli_stmt_fetch($stmt)). they mean separate things and since you already have error handling for the execute() call by using exceptions to handle the database statement errors, there's no point in having conditional error handling logic in your code.
  12. mac_gyver

    ^= means what in PHP language?

    it's actual a combined assignment and bitwise Xor (exclusive or). the starting value on the left is Xor'ed with the value on the right and becomes the new value on the left.
  13. mac_gyver

    How to see threads I "like"

    past version(s) of this ridiculous forum software had separate tabs/menus to let you access likes you have given or received. this is currently lumped together under REPUTATION ACTIVITY. this is a link to your's under your profile - https://forums.phpfreaks.com/profile/26806-notioncommotion/reputation/?type=forums_topic_post&change_section=1
  14. you are likely getting that same error when the the login works, but it is probably being hidden by a redirect. since you only use mysqli_stmt_free_result() if you are using mysqli_stmt_store_result(), which you aren't in the posted code, doesn't that mean that you shouldn't be using mysqli_stmt_free_result() at all? you need to switch to the much simpler PDO extension and use exceptions to handled db statement errors. it only takes 4 lines of code to replace the 11 lines you have from the sql query statement through to the fetch statement. $query = "SELECT id,recruits_number,sponsor_username,account_activation_status,id_video_verification_status,id_verification_video_file_url,username,password,primary_domain,primary_website_email,registering_country,registering_ip,registering_browser,registering_os,registering_isp,age_range FROM users WHERE $querying_column = ?"; $stmt = $pdo->prepare($query); $stmt->execute([$login_username_or_email_or_domain]); if(!$row = $stmt->fetch()) { // the email/username was not found // set up the failed login message } else { // the email/username was found, check the activation status and then verify the password hash to finish logging in // the fetched data is in the associative array $row }
  15. mac_gyver

    How to make it insert info from session

    this sounds like a bad design.
  16. it's even worse than that. you cannot use mysqli_error to report connection errors, since there's no connection to supply as a parameter. also, the OP's main code is using $conn->connect_error, which only works if the connection is using OOP notation, which it isn't. i'm pretty sure the OP has been shown/given the line of code needed to use exceptions for errors with the mysqli extension, since he has included it at various times in his code., and which would eliminate ALL this error handling logic from his code. i'm wondering if the OP is ready yet to switch to the much simpler and more consistent php PDO extension, that only has ONE possible calling syntax, that will cut the amount of code in half.
  17. mac_gyver

    Declaring Variable Hell

    for $_POST (and $_FILES) data, you should just detect that a post method form was submitted using if($_SERVER['REQUEST_METHOD'] == 'POST') { all the form processing code goes here... } then all form fields, except for unchecked checkboxs/radio-buttons, will be set. you would only need to use isset() or the Null Coalescing Operator for checkbox/radio-buttons. if you have the form processing code for more than one form on a page, you need to add 'control' logic within the request method test that then detects the value in a hidden field, and executes the correct section of form processing code. next, copying variables to other variables without any reason is just a waste of typing and clutters up the code. if you did nave a good reason, such as if trimming all the data, so that you can detect if all white-space characters were entered, you can do this using one line of code using array_map() with an appropriate call-back function (either php's trim function or a user written recursive trim function.) this will result in the set of trimmed data being placed in an array, where you would access elements in the resulting array variable in the rest of the code, rather than dealing with a bunch of discrete php variables. this will let you operate on the data as a set, using php array functions (see the next point.) lastly, for form processing code, if you have more than about three form fields, you should dynamically process the form data, by creating an array that defines the expected field names and any processing attributes, such as 'required', what type of validation, then loop over this defining array and use general-purpose code to process the data.
  18. it's generally not a good idea to store the same information in multiple places. if you already have the playercount and gameid stored in the playercount table, just use a JOIN query between the onlinegames table and the playercount table when you want to display the information. as to the performance of the posted code - 1) you need to prepare the UPDATE query once, before the start of the loop, and only execute it inside the loop with each set of values 2) is the onlinegames table gameid column defined as an index? if it's not, then every execution of the query will scan the table to find the row to update. also, i suspect that your $db->connect() method is creating a database connection each time it is called, which is a time consuming and wasteful process. you are also executing the SELECT query twice, once at the ->query() method call and then again at the ->execute() call. why are you doing that?
  19. the code you linked to in the post above at SOF is the slowest method possible, because it's repeatedly producing, preparing, and executing the same single-row sql statement inside of a loop. at a minimum, it should only produce and prepare the query once, before the start of the loop, then only get each row of data and execute the query inside of the loop. you also need to insure that you are using a true prepared query (PDO emulates prepared queries by default and therefor doesn't actual save the query planning done with a true prepared query when executing the same sql statement more than once.) the fastest method, as Barand posted, is to use a LOAD ... command. the next fastest is to use a multi-value(multi-row) query that INSERTs ... UPDATEs or REPLACEs (depending on how many fields you are dealing with, a REPLACE query may be better than in INSERT ... ON DUPLICATE UPDATE... query) as many rows as possible at one time (a few thousand is typical, based on the maximum packet size that the database server is set up to use - 1Mbytes is the default.) the next fastest would be a singe-row prepared query, done correctly, by only producing and preparing the query once before the start of any loop. the next fastest would be to run a non-prepared or an emulated prepared query inside the loop. the slowest would be a true prepared query, being prepared and executed inside of the loop, because both the prepare() and execute() cause a communication between php and the database server.
  20. mac_gyver

    Download file from mySQL database (blob)

    a) it is generally not a good idea to store files in a database (getting large data into and out of the database is a problem. and sql dumps are twice the size since they are done in hexadecimal.) databases are for storing data. file systems are for storing files. b) if you do store files in a database, you must store all of the file. the blob type you have used only holds 64K bytes. the file size your code allows is 5M bytes (and would take special handling to store since the default data packet size is 1M bytes.) the actual size of your test file is 102k bytes, which was then cut off at 64K when it was stored. c) the php code in download.php is trying to check the existence of and read the file as though it is stored in the file system, not in the database.
  21. mac_gyver

    months into php mysql and security is a headache

    if your comment/question is just about database security, that's easy to do. if an sql query has external/unknown data values being supplied to it, use a prepared query. if are no pieces of data being supplied to the sql query or there are but they are 100% known to be safe (were produced by your server-side code), use a non-prepared, regular query. you would also use a prepared query for the few cases where you need to execute the same sql query statement multiple times with different sets of input data. the key to making this easy is to use the simplest and least amount of implementation code, so that you are spending most of your time working on the logic that accomplishes a task, rather than on the implementation details. the only php code i/we have seen of your's on this forum is this - https://forums.phpfreaks.com/topic/307852-not-pulling-data/ that particular code can be simplified by - 1) using exceptions to handle database statement (connection, query, prepare, execute) errors, and in most cases let php catch the exception where it will use its error_reporting, display_errors, and log_errors settings to control what happens with the actual error information. you would display all errors when learning, developing, and debugging code/queries. when on a live/public server, you would log all errors. doing this only takes one statement to enable exceptions for the database extension you are using. you will then be able to remove all the conditional logic you have now that's trying to provide error handling for the database statements (in at least one case in that code, you are not reporting the error, so, the existing logic isn't always helping.) 2) use the much simpler php PDO extension. this will reduce the amount of code (you don't need to explicitly bind input or result data or use the get_result statement) and lets you treat the result from all queries the same. an added advantage to using the PDO extension is that the same php statements can be used regardless of the database type (you will still need to make any necessary changes to the actual sql query syntax for different database types.) with the mysqli extension, those statements are specific to the mysql (and cloned) database type. if you want or need to switch to a different database type - mssql, postgre, sqllite, ... , you will need to learn another set of php statements specific to that database type. 3) separate the different concerns in your code. the database specific code, that knows how to execute a query and fetch the data, is a different concern from the presentation code, that knows how to produce the output from the data. the way to accomplish this separation is put the database specific code above the start of the html document (or ajax response code), fetch the data from queries into appropriately named php variables, then use those variables in the correct place in the html document (or ajax response code.) this will get the clutter of the database code out of the html document, allow you to easily test if your code is producing the correct data, and treat the html document as a 'template' where you only have simple php code in the html document to use the data being supplied to it. also, by fetching all the data from any query, you eliminate synchronization errors, so there is no longer a need to close prepared statements. 4) php will automatically close database connections when the script ends, so unless you have a good reason to do so, don't close them in your code. a slightly more advanced thing you can do that will make your implementation code more general purpose, is to extend the database extension you are using with your own general purpose prepared/non-prepared query method,, that accepts the sql query statement and a second optional array parameter of input data. the method code will test for the optional input data and run the code needed for a prepared query if there is input data, and run a non-prepared, regular query if there is not. the code from that thread, making use of items 1-4, would (untested) simply be - <?php // since this code is apparently only providing a response to an ajax request, only execute it if the expected input is set if(isset($_GET['term']) && $_GET['term'] != '') { // make the pdo connection - you would typically put common code like this into an external .php file, then require it when needed $DB_HOST = 'localhost'; $DB_USER = 'root'; // you should not use the root account in your application. make a specific user with just the permissions that your application needs $DB_PASS = ''; $DB_NAME = 'st'; $DB_ENCODING = 'utf8'; // db character encoding - set to match your database table character set (utf8 is a common/best choice) $pdo = new pdo("mysql:host=$DB_HOST;dbname=$DB_NAME;charset=$DB_ENCODING",$DB_USER,$DB_PASS); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the error mode to exceptions $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false); // run real prepared queries $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC); // set default fetch mode to assoc // database specific code $search_result = []; // define/initialize to an empty array $sql = "SELECT id, state FROM loc WHERE state LIKE ?"; $stmt = $pdo->prepare($sql); $stmt->execute([$_GET["term"] . '%']); $search_result = $stmt->fetchAll(); // presentation code if(empty($search_result)) { // no data to display - it's usually clearer if you handle error/negative results first echo "<p>0</p>"; // this what your original code output when there were no matching rows } else { // data to display foreach($search_result as $row) { echo "<p>" . $row["state"] . "</p>"; } } }
  22. mac_gyver

    SQL injection Hysteria? Or not?

    firstly, you should NOT modify/sanitize user input, except perhaps to trim it. by modifying it, you are changing the meaning of it. (a few versions ago of this forum software, the email addresses were 'sanitized' inconsistently, resulting in multiple values mapping to the same account and a hacker was able to do a password recovery for an admin using the hacker's email address, which allowed the hacker to log in as that admin and all the user's data was copied.) what you should do instead is to just validate the user input, to make sure it is suitable within the context of your application. if the data is not valid, don't use it at all and output a message to the user telling them what was wrong with the submitted data. next, the regex pattern you have in your example isn't what you will use for all possible user input. things like names, text content (like we are typing here in the forum) , or email addresses require other characters like single-quotes or strings that are hexadecimal (0-9 and a-f) values. as soon as you allow these and put them directly into the sql query statement, you are open to sql injection. when you get to the database layer, all you should be concerned with is protecting against sql special characters in the data from breaking the sql query syntax (which is how sql injection is accomplished.) you should not care about where the data came from, what it means, or what type of validation/sanitizing it may or may not have received prior to that point. the simplest , most general-purpose, and surest way of providing this protection is to use a prepared query (assuming you are using the much simpler php PDO extension. the php mysqli prepared query programming interface is overly complicated and inconsistent, resulting in either a lot of extra typing for each query or in a bunch of slow code if you write a single-point general-purpose prepared query function/method.) another advantage to using prepared queries are for the few cases where you need to execute the same sql query multiple times within an instance of your script. by preparing the query once, then just executing it with different sets of input data, you will save about 5% of the execution time for most, straight-forward, queries.
  23. OR if you use the same named hidden field for all the forms, 'action' for example, each with a unique value, you can eliminate any isset() tests for that field since it will be set if the request method is post.
  24. mac_gyver

    Need help with an account update snippet

    this code is filled with mistakes (the incorrect INSERT query, a form field type = 'company', a changing/non-existent variable name) and the symptom of it seemingly working at one point, then not at another, is due to some of those mistakes and the changing data being tested that doesn't mean what you think. by testing for an empty string '""/empty() in the logic, you cannot tell if the data exists but is empty or if the data doesn't exist at all. the way to initially SELECT and retrieve data to be edited is to define an empty array variable, $post for example, before the start of the form processing code, copy the submitted form data to this variable inside of the form processing code, then after the end of the form processing code, if the variable is empty query for and retrieve the existing data and assign it to this variable. use the contents of this variable when outputting the values in the form fields. next, if the accounts db table is the primary user table, i.e. a row will exist if the user exists, then the only query in this edit form processing code should be one UPDATE query (i suspect you have repeated this code and query for each form field.) if this is instead an add-on db table, designed only to hold profile information, where there many not initially be a row for any user, than the query you have in this edit form processing code should be one INSERT ... ON DUPLICATE KEY UPDATE ... query, with the user_id being defined as the unique key that triggers the duplicate key part. your form processing code should also validate the submitted data, storing validation errors in an array variable, then only use the submitted data if it is valid. if you have repeated the posted code/query(ies) for each form field, you should instead just have one consolidated form processing code with one query that operates on all the form fields at once. you should also use prepared queries when supplying data to an sql query statement (no matter how good you think your sanitizeString() function is, there are hackers out there with libraries of injectable sql that can probably get past it, especially if you have not set the character set that php is using to match your database, and you should only apply any sort of sql protection to the data being supplied to a query, not to data that is being output in form field values and you shouldn't be trying to strip slashes and certainly not from data after you have retrieved it from your database.)
  25. mac_gyver

    Help with sqlite

    it would be nice if you posted your code that's setting the $search variable (you could be doing something that you think is correct, but isn't) and your code using $result (you could be doing something that you think is correct, but isn't.)
×

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.