Jump to content


Staff Alumni
  • Content Count

  • Joined

  • Last visited

  • Days Won


Everything posted by mac_gyver

  1. mac_gyver

    Use of conditions (Switch/IF)

    lol, i stared to post a reply, but the authors of this forum software made it almost impossible to compose a reply containing quotes, code, and new text, that i couldn't produce the result that i wanted. start by learning what an if(){} statement looks like, and what it does when the condition being tested is a true value. then, write three if(){} statements, one testing each info_condx()
  2. mac_gyver

    Use of conditions (Switch/IF)

    i recommend that you slow down and think about what you are trying to accomplish. the code you posted above only has one if(){} statement. the method i suggested starts with three separate if(){} statements.
  3. mac_gyver

    Use of conditions (Switch/IF)

    i would start with three separate if(){} statements to test each of the cond1, 2, and 3 values. for any that are true, i would increment a counter and set a common variable with the corresponding A, B, or C content. after the above logic, if the counter is zero, output the E content. if the counter is one, output whatever is in the common variable that was set in the above logic. else output the D content.
  4. mac_gyver

    Help needed with database search and update

    a bunch of recommendations, most of which will reduce and simplify the code, making it possible to spend more time on what the code is trying to accomplish, rather on spend time on the tedious implementation details - 1) put all the code on one page. the resulting code should be laid out as follows - initialization - code that defines, creates, or requires things the php code on the rest of the page needs to do its job. post method form processing - code to process $_POST data. note: your search form should use method='get'. post method forms are used when affecting data on the server or performing an action, such as sending email. get method forms/links are used when you are controlling what will be gotten and displayed on a page. the code to INSERT/UPDATE data in the database would be placed in this section of the code. it would first detect that a post method form was submitted, validate the input data, then if there are no validation errors, use the submitted data when the query is executed. get method 'business' logic - this is the code that knows how to retrieve or produce data that's needed to display the page. html document - the result from items 1-3 should be stored in php variables. these variables are the input data to html document. you can either use a 3rd party template engine or use simple php statements in the html document to take the input data and produce the dynamic sections of the html document. 2) validate all input data before using it. for your search form, what should happen if the page gets requested with no $_GET parameter? should you set up a default value or output an error message for the user (you probably don't want to generate php errors, which is what will happen now)? what should happen if the search string is empty? should the code match all rows or output an error message to the user telling them that the search term cannot be empty? if you store validation errors in an array, you can test at any point if there are or are not any errors by testing if the array is not empty or is empty. to display the errors at the appropriate point in the html document, either loop over the array or just implode it. 3) use 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. when learning, developing code/queries, and debugging problems, you should display all php errors. when code is running on a live/public server, you should log all php errors. 4) use prepared queries when supplying data to an sql query, with place-holders in the sql statement for each value, then supply the data when the query gets executed. you also need to switch to use the php PDO extension, it is much simpler and more consistent than the mysqli extension. 5) don't use SELECT * in sql query statements. list out the columns you want to select. this helps avoid mistakes and makes your code/query self-documenting. 6) only use php code for things that are 'dynamic'. if you are outputting mostly static html, don't waste your time typing a bunch of php echo statements around each line of it. 7) you need to validate the complete page at validator.w3.org 8 ) don't use $_REQUEST variables. if you expect post data, use $_POST variables. if you expect get data, use $_GET variables. if you expect cookie data, use $_COOKIE variables. 9) php automatically closes database connections when the script ends, so, you don't have to have code to do this. 10) you need to decide if and how you are going to update multiple rows of data. you currently have a single form (it's missing the closing </form> tag) with multiple submit buttons in it, which will cause all the form data to be submitted when any button is pressed. for this case, you should instead have one or two submit buttons before/after the program loop and only repeat the form data fields inside the program loop. also, in order to update multiple rows of data at once, the form field name(s) must be arrays with the array index being the id of the row of data that corresponds to each form field. when the array(s) of form data get submitted, you can use a foreach(){} loop to get the id and the value to use in a database query. an alternate method is to produce a separate form for each row of data, which will update just that row of data when the form is submitted. 11) your posted addtostock.php code doesn't have a database connection, so, if you manage to get your form to submit data to it, there will be a bunch of php errors associated with the connection. this problem will go-a-way when you put all the code on one page.
  5. to log your own information to a file, use file_put_contents() with the FILE_APPEND flag. in programming, there is no 'automatic', the computer only does exactly what someone has written code to tell it to do. to send an email from your .php script, you can use php's mail() function or one of the 3rd party mail classes - phpmailer or swiftmailer
  6. if you are seeing the php code in the browser, it means that the php language engine is not being invoked. given that you were previously getting php errors from this code, about the only thing that comes to mind is if you switched how you are opening the page the form is on. you should be using a URL like - http://localhost/your_form.php (or .htm or .html) to open the form. If you are clicking directly on the file where the form code is saved, you are actually opening the file in the browser, rather than going through the web server. if the form is being opened through the file system, when you submit it, the .php page will be opened directly in the browser through the file system too, not through the web server.
  7. a php syntax error means you basically turned in a writing assignment and it received red mark(s) on it for being written wrong. the error means that php encountered a variable, while it was still expecting some closing punctuation. if you look at the lines of code leading up to the line where the error is being reported, you will notice that the echo '....' statement on the line above is missing the closing ;
  8. you have two nested <form> tags and the second one is ignored by the browser. since the first one doesn't contain a method='post' attribute, the data is submitted as $_GET data and will be submitted to the same URL the form is on. remove the first <form> tag and the form will submit $_POST data to the URL that you have in the action='...' attribute.
  9. mac_gyver

    Need random and unique but its not

    the fix is to define what you want, then write and test the code to do it. the history table appears to be where the card state is remembered? when a new game is started, i would insert 21 rows, with card ids 1-21, with the userid/date, into the history table, with a column that indicates if the card id is 'used' a 0 = not used, a 1 = used. to generate a set of three new cards, retrieve the card ids from the history table that have not been used. if the number of unused card ids is zero, the game is over. store the unused card ids into an array, shuffle them, and pick three ids. update the history rows to set the 'used' column to a 1 for the three ids that were picked and display the cards that correspond to the three ids. when retrieving the card information for the card ids, run one query that gets the data you want in the order that you want it (don't run SELECT queries inside of loops.) you should also not put 'dynamic' data values directly into the sql query statement. we don't know where the $loggedin value comes from, but if it could have come from user supplied data, it could be used to inject sql. you should use a prepared query when supplying potentially unsafe data to an sql query statement.
  10. mac_gyver

    how to update null

    the relevant query is failing to execute, probably due to a problem with a data value being supplied to the query. the execute() call is failing in this case and is returning an error, if you had error handling for the execute() calls. the WHERE clause in the queries are true, since the first SELECT query is matching its data. in one of your threads, i went to the trouble of reviewing your code and giving a list of recommendations. one of them pointed out that the execute() calls can fail, that you need to have error handling for them, and that you should simply use exceptions to handle database statement errors. i recommend that you review points #6 to #9 at the following link and actually use the information that is being provided in the replies to your threads - https://forums.phpfreaks.com/topic/307451-trying-to-understand-the-logic-of-the-if-and-else-statement/?do=findComment&amp;comment=1559317 short-answer - 1) enable exceptions (the line of code you need is posted in the linked to reply), 2) remove the existing if/else 'sql statement failed' message logic that's testing the mysqli_stmt_prepare() statements, 3) replace each of the mysqli_stmt_init($conn) and mysqli_stmt_prepare($stmt, $sql) pairs with a call to mysqli_prepare($conn,$sql), 4) remove the while(){} loop you are using to fetch a single row of data and just fetch the data, and 5) in another thread i pointed out that when you have an exit(); statement, you don't need an else{} around the rest of the code, because code execution won't run past the exit and you can remove the else{}. with all the unnecessary bits (programming pun intended) removed from the code, you should end up with something that looks like this - <?php // select the user membership data $sql = "SELECT * FROM memberships WHERE user_uid = ?"; $stmt = mysqli_prepare($conn,$sql); mysqli_stmt_bind_param($stmt, "s", $_SESSION['u_uid']); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); if(!$row = mysqli_fetch_assoc($result)) { echo "The requested membership row was not found."; } else { if ($row['subscriptionplan'] === 'Level 1' && $row['activate'] == 0 && $row['level1promo_activate'] == 0) { header("Location: index.php?level1=notactivated"); exit(); } if ($row['subscriptionplan'] === 'Level 1' && $row['activate'] == 1 && $row['emailreminder'] == 0 && date("Y-m-d H:i:s") > $row['paidbydate'] && $row['paid'] == 0 && $row['overdue'] == 0) { $sql = "UPDATE memberships SET paidbydate = ?, emailreminder = ?, overdue = ? WHERE user_uid = ?; "; $stmt = mysqli_prepare($conn,$sql); mysqli_stmt_bind_param($stmt, "siis", $paidbydate, $emailreminder, $overdue, $_SESSION['u_uid']); mysqli_stmt_execute($stmt); header("Location: index.php?level1=overdue"); exit(); } if ($row['subscriptionplan'] === 'Level 1' && $row['activate'] == 1 && $row['emailreminder'] == 1 && date("Y-m-d H:i:s") > $row['paidbydate'] && $row['paid'] == 0 && $row['overdue'] == 1) { $sql = "UPDATE memberships SET subscriptionplan = ?, subscriptionplandate = ?, fees = ?, expirydate = ?, paidbydate = ?, emailreminder = ?, overdue = ?, activate = ? WHERE user_uid = ?; "; $stmt = mysqli_prepare($conn,$sql); mysqli_stmt_bind_param($stmt, "ssissiiis", $subscriptionplandelete, $subscriptionplandatedelete, $feesdelete, $expirydatedelete, $paidbydatedelete, $emailreminderreset, $overduedelete, $activatedelete, $_SESSION['u_uid']); mysqli_stmt_execute($stmt); header("Location: index.php?level1=cancelled"); exit(); } if ($row['subscriptionplan'] === 'Level 1' && $row['activate'] == 1 && date("Y-m-d H:i:s") > $row['expirydate'] && $row['paid'] == 1) { $sql = "UPDATE memberships SET subscriptionplan = ?, subscriptionplandate = ?, fees = ?, expirydate = ?, paidbydate = ?, emailreminder = ?, overdue = ?, activate = ? WHERE user_uid = ?; "; $stmt = mysqli_prepare($conn,$sql); mysqli_stmt_bind_param($stmt, "ssissiiis", $subscriptionplandelete, $subscriptionplandatedelete, $feesdelete, $expirydatedelete, $paidbydatedelete, $emailreminderreset, $overduedelete, $activatedelete, $_SESSION['u_uid']); mysqli_stmt_execute($stmt); header("Location: index.php?level1=expired"); exit(); } } once you enable exceptions, php will catch the database statement errors, where it will use its error_reporting, display_errors, and log_errors settings to control what happens with the actual error information. if you have php's error_reporting set to report all errors and either display them or log them, you should start getting errors at the relevant execute() calls telling you why the query is failing.
  11. mac_gyver

    how to space out my review texts

    the mt_rand() is there to help insure that the image will be requested from the server, rather than to use a cached image.
  12. mac_gyver

    how to space out my review texts

    you are getting two images because your query is not doing what you want, probably because you are just copying things together instead of writing the code so that it does what you have defined. you are querying for all the rows from the users table. you should be querying for just the row that matches the current logged in user, and as has already been written in a reply, don't use a loop to retrieve data when a query will match just one row. you should also be using a single JOIN query, between the users and the profileimg tables. in fact, for what you are doing, getting the status from the profileimg table, you only need to query that table. you are not actually using any data from the users table query that you don't already have from your login session variable.
  13. mac_gyver

    Concat to Un concat?

    storing each piece of data in its own row would make solving this simple. you would just JOIN the SELECT query that you are using now to get the CouponsID values with the table holding the coupon details. storing each piece of data in its own row will also simply duplicate checking (assuming you are checking now), since you can set up the EID and CouponsID columns as a composite unique index, and prevent duplicates from being inserted/updated. btw - you should not be putting data values directly into sql query statements. you should be using prepared queries, with a place-holder for each value and then supply the values when you execute the query. lol - what is the following from your query - you are breaking out of the php double-quoted string, just to concatenate a comma back into the query. 🙄
  14. mac_gyver

    session already started error

    ^^^ that's answered in the php.net documentation.
  15. mac_gyver

    session already started error

    you need ONE session_start() statement on any page that sets or references session variables. the error you are getting is because you have executed a session_start() prior to the one where the error is occurring at. the session_start() statement should come near the top of your main file, in an 'initialization' section, where you define, create, and require (you should use require, rather than include or include_once) things that the rest of the code on the page needs. best guess is the code you have posted is being included/required by another file and that main file has a session_start() statement in it. if so, just remove the session_start() in the posted code.
  16. you can put the form and the form on different pages, but by putting them on separate pages, you will have the disadvantages you are experiencing in this thread, of having to redirect back to the form upon an error and not being able to repopulate the form fields. this also takes more code. you can redirect to the same page, but your program logic must prevent further redirects? are you at the point where you can figure out how to prevent the redirect loop?
  17. the redirect error is because you are redirecting to the same page and the logic you have on the page causes more redirects. the way to fix this is to correct the logic, firstly by not redirecting all over the place. i posted some example code about 5 replies above this (the new forum software doesn't number replies, so i cannot refer you to a post number), using this structure for form processing and the form will eliminate the need for all but one redirect and that redirect will be inside the post method form processing code, which won't be executed upon the redirect since there won't be any post data after the redirect.
  18. here is where reading the introductory sections in the php.net documentation will help (i linked to it above.) you will learn what actually exists and how to use it.
  19. the following is a single page password reset example, showing the recommendations listed above - <?php // define some 'helper' functions - these would typically be defined in an external .php file and 'required' when needed // apply html htmlentities to a value function _ent($val) { return htmlentities($val); // this uses the current/default character encoding setting } // return an element from an array - used to reference array elements that might not be set function _element($arr,$index) { return isset($arr[$index]) ? $arr[$index] : ''; } // recursive function to trim data. function _trim($val) { if(is_array($val)) { return array_map('_trim',$val); } else { return trim($val); } } // define an array of the expected/required form fields $fields = []; $fields['user_uid'] = ['label'=>'Username']; // i suspect the user_uid is actually the username $fields['temporary_password'] = ['label'=>'Existing Password']; // suspect temporary pwd is a generated pwd, in any case it is the existing password $fields['password'] = ['label'=>'New Password']; $fields['confirm_password'] = ['label'=>'Confirm New Password']; $errors = []; // define an array to hold validation errors $post = []; // define an array to hold a working copy of the submitted form data // form processing code if($_SERVER['REQUEST_METHOD'] == 'POST') // this is a general purpose way of detecting if a post method form has been submitted. { // get a trimmed copy of the submitted form data $post = array_map('_trim',$_POST); // validate the submitted data // check that the required fields are not empty foreach($fields as $field=>$arr) { if($post[$field] == '') { $errors[$field] = "{$arr['label']} is empty."; } } // check if the password/confirm_password match if(empty($errors['password']) && empty($errors['confirm_password']) && $post['password'] != $post['confirm_password']) { $errors['password'] = "The {$fields['password']['label']} and {$fields['confirm_password']['label']} are not the same."; } // if the new password must meet any length or 'strength' requirements, validate those here... // at this point, if there are no errors, use the submitted form data if(empty($errors)) { // use the data in $post here... require 'dbh.php'; // get the current password for the user $sql = "SELECT user_password FROM users where user_uid = ?"; $stmt = $pdo->prepare($sql); $stmt->execute([$post['user_uid']]); if(!$row = $stmt->fetch()) { // the user doesn't exist $errors['user'] = "The username/password is incorrect."; // a generic message to help prevent finding valid usernames } else { // the user does exist, check the existing password if(!password_verify($post['temporary_password'],$row['user_password'])) { // password doesn't match $errors['user'] = "The username/password is incorrect."; // a generic message to help prevent finding valid usernames } else { // password does match, update the password $sql = "UPDATE users SET user_password = ? WHERE user_uid = ? "; $stmt = $pdo->prepare($sql); $stmt->execute([password_hash($post['password'], PASSWORD_DEFAULT),$post['user_uid']]); } } } // at this point, if there are no errors, the form processing code was successful if(empty($errors)) { // do whatever you want when the password reset was successful } } // output the html document starting here... ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Reset password</title> </head> <body> <?php // display any errors if(!empty($errors)) { echo implode('<br>',$errors); } ?> <form method="POST"> <input type="text" name="user_uid" placeholder="Username" value='<?php echo _ent(_element($post,'user_uid')); ?>'> <br> <input type="text" name="temporary_password" placeholder="Existing Password" value='<?php echo _ent(_element($post,'temporary_password')); ?>'> <br> <input type="text" name="password" placeholder="New Password" value='<?php echo _ent(_element($post,'password')); ?>' > <br> <input type="text" name="confirm_password" placeholder="Confirm New Password" value='<?php echo _ent(_element($post,'confirm_password')); ?>'> <br><br> <button type="submit" name="submit" class="button">Reset Password</button> </form> </body> </html> you don't have to understand OOP notation in order to use it. calling an OOP class method is really no different than calling a procedural function. compare the PDO statements on ~ lines 70-72 and 88-89 with the massive number of mysqli statements you have in your code, and decide which you would rather be using. you will also note that the sql syntax for ? prepared query place-holders is the same between mysqli and PDO, so you don't have to change any of the sql syntax.
  20. as to the error, an else {} statement requires a corresponding opening if(){} statement. i can only guess that you are trying to add an else {} because you have some code (the success redirect) in the wrong place and you are not actually reading the code and seeing where the opening { and closing } are at now. before going any further, you need to add missing features and simplify the existing code. at a minimum do the following - 1) detect that a post method form has been submitted before referencing any of the $_POST data. 2) validate all input data before using it. use an array to hold validation error messages. this will let you validate all the data at once and then display all the errors when you re-display the form. 3) the form processing code and the form need to be on the same page. this will eliminate all the header() redirects and it will let you re-populate the form with the submitted data when there is a validation error, so that the visitor doesn't need to keep reentering the same data over an over. 4) don't copy variables to other variables without a good reason. one good reason when processing user submitted values would be to trim() the data, so that you can detect all white-space characters. you can do this with a single line of code that operates on the data as a set. 5) password_hash() is used on the password you are going to insert/update in the database table. password_verify() is used to compare the stored hashed password with a submitted password. all other uses of these that you have in your code now are not doing anything useful and in the case of trying to compare the stored hashed password with the submitted password, you need to use password_verify() after you have fetched the stored hashed password. 6) don't use mysqli_stmt_init() and mysqli_stmt_prepare(). just use mysqli_prepare(). it does the same thing with one statement. 7) use exceptions to handle database statement (connection, query, prepare, execute) errors. this will simplify the code (you can remove the conditional logic you have now) and give you error handling for all the statements (the execute call can fail too, but you don't have any error handling for it.) to enable exceptions for the mysqli extension, add the following line before the point where you are making the database connection - mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); 8 ) don't use mysqli_stmt_get_result() it results in non-portable code. this statement may work on your development system and current web host, but it may not on a different web host. if you move to a different host, you may have to rewrite the code. it is better to avoid using statements that may not exist. in fact, you need to switch to use the php PDO extension (Barand posted an example in one of your threads.) the PDO extension doesn't have any statements that may not exist and it is overall simpler and more consistent to use than the mysqli extension. 9) the query in the code will at most match one row. don't use a loop to fetch the data. this is just cluttering up your code with unnecessary logic and syntax. Keep It Simple - KISS.
  21. i'm not sure if (programming pun intended) or what the question is? if you are asking what a php if/else statement does, please see the control structure section of the php.net documentation - http://php.net/manual/en/language.control-structures.php if you are asking when you should use an if(){} or if(){}else{} statement or what code you should put in each part of the if/else statement, that depends on what you have defined you want the code to do. conditional statements control which code gets executed, based on the Boolean result of the expression being evaluated. the if(){...} block of code gets executed if the expression evaluates to a true value. the else {...} block of code gets executed if the expression evaluates to a false value. if you want to redirect the user to a different page if they are not logged in, you would use an if(){...} statement. the expression being evaluated would be a value that indicates the not logged in state. the code that gets executed would perform the redirect. btw - in the 1st piece of code, the first else {} is not need and should be removed, because the if(){} code exits and halts program execution when the expression is true. just put the remainder of the code after the closing } of the if(){} statement.
  22. your page is redirecting to itself, over and over, until the browser has had enough. your program logic is not correct. you need to decide what the code on your page is going to do if the user is logged in and if the user isn't logged in, starting with what is the purpose of this page? is it the login form processing and login form (based on the loginsystem in the path), or is it the site's main index.php page? if you are trying to make a single page that has form processing code and the form on it, the only redirect you should have is at the end of successfully completing the post method form processing code, in which case you should redirect to the exact same URL of the page to cause a get request for the page so that the browser won't try to re-submit the post data if you refresh the page or navigate away from and back to it.
  23. mac_gyver

    Need help Rename the image while uploading.

    if you are storing uploaded files associated with each user, wouldn't using the user id as a leading part of the file name, followed by a separator character, then the file category, make sense? you can then find all the files associated with a user by doing a wild-card file match starting with the user's id and separator character.
  24. mac_gyver

    ipn simulator not working on 000webhost...

    this is likely due to a + near the end of the payment date for the time zone, and when you use http_build_query() on the data, this gets treated as is (a space), rather than a literal + , which should end up being a %2B urlencoded value. you should log the received $_POST data so that you can see what it is. if the payment date looks like - Wed+Jul+4+2018+10%3A15%3A11+GMT+0000, you will need to handle the last + differently in the code. next, either use or examine the 'official' php paypal listener code, to see how the + near the end of the payment date gets treated - https://github.com/paypal/ipn-code-samples/tree/master/php
  25. mac_gyver

    Displaying records from database using enum

    you will want to do something that was posted about an hour ago on one of the other help forums, and use the same where clause in both queries.

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.