Jump to content

mac_gyver

Staff Alumni
  • Content Count

    4,211
  • Joined

  • Last visited

  • Days Won

    104

mac_gyver last won the day on November 10

mac_gyver had the most liked content!

Community Reputation

437 Excellent

1 Follower

About mac_gyver

  • Rank
    Staff Alumni

Profile Information

  • Gender
    Not Telling

Recent Profile Visitors

146,258 profile views
  1. 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.
  2. 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
  3. 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 }
  4. mac_gyver

    How to make it insert info from session

    this sounds like a bad design.
  5. 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.
  6. 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.
  7. 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?
  8. 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.
  9. 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.
  10. 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>"; } } }
  11. 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.
  12. 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.
  13. 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.)
  14. 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.)
  15. mac_gyver

    Query Statement Help

    mysqli_fetch_fields() doesn't do what you think. it fetches information about the fields. it doesn't fetch data and you would have been getting php undefined index errors from your code to alert you to the problem. you need to ALWAYS have php's error_reporting set to E_ALL and when learning, developing, and debugging code, have display_errors set to ON and when on a live/public server have display_errors set to OFF and log_errors set to ON. you would want to use mysqli_fetch_assoc() to fetch the data.
×

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.