Jump to content

mac_gyver

Staff Alumni
  • Posts

    5,352
  • Joined

  • Days Won

    173

Community Answers

  1. mac_gyver's post in I'm getting a session error was marked as the answer   
    the correct place to assign a value to the session variable is in the post method form processing code, at the point where you have confirmed that the username and password have been matched (it is currently not at this point in the code and needs to be corrected.) it should not be assigned a value in any other place. therefore, remove the assignment statement you currently/still have in sayfam.php. the debugging line of code, with print_r($_SESSION, true), should still be in sayfam.php, until you get this to work, since is shows if the session variable is set and what value it contains.
  2. mac_gyver's post in Help with hiding search titles was marked as the answer   
    conditional statements exist in programming languages so that you can write code that makes decisions when it runs, such as only outputting markup when there's data to display.
    the existing code has a conditional test in it to only output the markup inside the tbody if there is data to display. wouldn't the answer to your question be to move the start of that conditional test so that it only outputs the table/thead markup when there is data to display?
  3. mac_gyver's post in Using PHP and Ajax to show ORDERS by Year without refreshing page was marked as the answer   
    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.
     
  4. mac_gyver's post in Unable to display username in Table was marked as the answer   
    just use a single JOIN query to do this.
    next, you should always list out the columns you are SELECTing in a query so that your code is self-documenting. you should build your sql query statement in a php variable, to make debugging easier and help prevent syntax mistakes, and you should set the default fetch mode to assoc when you make the database connection so that you don't need to specify it in each fetch statement.
    the reason why your current code doesn't work, is because fetchAll(), the way you are using it, returns an array of the rows of data. if there are three rows in the company table, you will have an array with three rows in it, with each row having an assignedto element. you can use print_r() on the fetched data to see what it is.
     
  5. mac_gyver's post in Sending emails to multiple email ids with nested loop was marked as the answer   
    how many email addresses per vendor? if there's only one, you don't need the 2nd foreach() loop to fetch it, just directly fetch the single row without using a loop.
    next you don't even need the 1st foreach() loop, just implode $_POST['vendor'] to make a comma separated list, then use FIND_IN_SET(vendor,?) in the WHERE clause to match all the rows in one query, then just use the result set from that single query. if you use PDO fetchAll() with the PDO::FETCH_COLUMN fetch mode, you will get a one-dimensional array of just the email addresses, that you can directly implode() to produce the comma separated list of email addresses.
  6. mac_gyver's post in How to validate if certain value is duplicate or if certain input field is not filled using PHP AJAX Javascript was marked as the answer   
    I've written at least twice that the ->create() method must return a success or failure value that you test in the calling code. the database specific code in the ->create() method is where that information is known at.
    here's what your create.php should look like (without the multiple column duplicate determination code) -
    <?php // when using ajax, the only thing this code will do is handle the post method form processing // you can save resources on non-post requests by putting all the code inside the request method test // initialization //Headers header('Access-Control-Allow-Origin: *'); header('Content-Type: application/x-www-form-urlencoded'); header('Access-Control-Allow-Methods: POST'); header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With'); // use 'require' for things your code must have for it to work require '../../config/database.php'; require '../../models/post.php'; //Instantiate db $database = new Database(); $db = $database->connect(); // define the $table and $fields for the Create operation $table = 'skandi'; $fields = []; $fields['sku'] = ['label'=>'SKU','validation'=>['required']]; // add other field definitions here... //Instantiate post for the Create operation $product = new Post($db,$table,$fields); $post = []; // array to hold a trimmed working copy of the form data $errors = []; // array to hold user/validation errors // post method form processing if($_SERVER["REQUEST_METHOD"]==="POST") { //Get raw data $json = json_decode(file_get_contents("php://input"),true); // trim all the input data at once $post = array_map('trim',$json); // if any input is an array, use a recursive trim call-back function here instead of php's trim // validate all inputs foreach($fields as $field=>$arr) { if(isset($arr['validation']) && is_array($arr['validation'])) { foreach($arr['validation'] as $rule) { switch ($rule) { case 'required' : if($post[$field] === '') { $errors[$field] = "{$arr['label']} is required"; } break; // add code for other validation rules here... } } } } // if no errors, use the input data if(empty($errors)) { //Create if(!$product->create($post)) { // initially, just setup a canned message for the sku column $errors['sku'] = "SKU is already in use"; // the code to detect which of multiple columns contain duplicates would replace the above line of code } } // if no errors, success if(empty($errors)) { $response = [ 'message' => "Created Successfully" ]; } else { $response = [ 'message' => implode('<br>',$errors) ]; } echo json_encode($response); } the corresponding ->create() method would be -
    public function create($data) { // build the sql query $set_terms = []; $params = []; foreach(array_keys($this->fields) as $field) { $set_terms[] = "`$field`=?"; $params[] = $data[$field]; } $sql = "INSERT INTO `$this->table` SET " . implode(',',$set_terms); $stmt = $this->conn->prepare($sql); try { // a 'local' try/catch to handle a specific error type $stmt->execute($params); // if you are at this point, the query executed successfully return true; } catch (PDOException $e) { if($e->errorInfo[1] == 1062) // duplicate key error number { return false; } throw $e; // re-throw the pdoexception if not handled by this logic } } as to the server-side validation logic, you should validate each input separately and setup a unique and helpful message for each validation error. the code posted in this reply shows how to use a data-driven design to dynamically validate the data and build the sql query. however, it just occurred to me that the product characteristics (size, weight, height, length, and width) change depending on the selected productType, so the data-driven definition would need entries for each productType value (you should also have a separate product characteristic table, rather than columns in this main table for these characteristic values, where you would only insert rows for each characteristic that exists for each defined product.)
    for debugging, just temporarily output (echo/print_r/var_dump) things in the php code, and send everything to the console log in the javascript -
    success: function (data) { console.log(data); alert("successfully posted"); },  
  7. mac_gyver's post in sign up issues with username/email validation was marked as the answer   
    you have far too much code for this task. it is filled with repetitive logic, copying of variables to other variables for nothing, and while it is adding user/validation errors to an array, it isn't testing that array for the main activity of executing the INSERT query, which is why it is always inserting the new data values. i recommend that you start over, with just the logic you need - Keep It Simple (KISS) and Don't Repeat Yourself (DRY.)
    you should make one database connection in your main code, then supply it to any function that needs it, as a call-time parameter. you should use the much simpler and more modern PDO database extension. you should also use exceptions for database statement errors (the PDO extension always uses exceptions for any connection error and starting with php8 always uses exceptions for the rest of the statements that can fail - query, prepare, execute, and exec.)
    your post method form processing code should -
    detect if a post method form has been submitted keep all the form data as a set, in a php array variable trim all the input data at once. after you do item #2 on this list, you can trim all the data using one single line of code validate each input separately, storing user/validation errors in an array, using the field name as the array index after the end of the validation logic, if there are no errors (the array holding the errors will be empty), use the submitted form data as already stated, the correct way of determining if uniquely defined database columns/fields are duplicate, is to just attempt to insert the data and test if the query produced a duplicate index error number in the exception catch logic. for all other error numbers, just rethrow the exception and let php handle it. since you have more than one unique field, it is at this point where you would execute a (one) SELECT query to find which fields contain duplicate values. you would add error messages to the array holding the user/validation errors for each field that is found to contain duplicate values.  after the end of post method form processing logic, if there are no errors, redirect to the exact same url of the current page to cause a get request for the page if you want 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. if there are errors at step #5 or #7, the code will continue on to display the html document, display any errors, redisplay the form, populating the fields with any existing form data. any dynamic value that gets output in a html context needs to have htmlentities() applied to it to help prevent cross site scripting.
  8. mac_gyver's post in is there an ideal way to counter a brute force attempt? was marked as the answer   
    the existence or absence of a session is under the control of the client/script making the requests to your site. you cannot use session (or cookie) data to detect or control the login attempts, since the client/script can simply not propagate the session id (or cookie) between requests and they will get a new session. you must store the data needed to detect or control the login attempts in a database table.
    you have two pieces of identifying information from the requests, the ip address (where the request came from and where you will send the response back to, along with any session id cookie or remember me cookie token) and the username/email for the login attempt. you would store the datetime, ip, and username/email for each failed login attempt, as a separate row, in a database table. it is this data that you would test to detect and control the login attempts.
    also, you don't 'lock' the accounts, you rate limit the login attempts. if a user is already logged in, they should still be able to access the site, i.e. they are won't be attempting to login, since they already are logged in.
  9. mac_gyver's post in Echo not outputting anything! was marked as the answer   
    there's nothing wrong with the POSTED code (just tested.) errors like this are usually caused by copy/pasting code that's been published on the web, with smart/curly quotes, which then produce php errors since those type of characters have no meaning in php, but which get converted back to straight quotes when code gets posted on a programming help forum, and therefor work when tried.
    delete and re-type the line of code.
  10. mac_gyver's post in Trying to create a schedule of games... was marked as the answer   
    what output are you getting on the web page? if it's a blank page, what does the 'view source' in your browser show? can you echo a string using php code? is your code doing any redirects that could discard any output from the web page if php's output_buffering is ON?
    do you have php's error_reporting set to E_ALL and display_errors set to ON, preferably in the php.ini on your system, so that php will help you by reporting and displaying all the errors it detects? stop and start your web server to get any changes made to the php.ini to take effect and check that the settings actually got changed to those values by using a phpinfo(); statement in a .php script file.
    do you have error handling for all the database statements that can fail - connection, query, prepare, execute, and a few others? the simplest way of adding error handling, without adding conditional logic at each statement, is to use exceptions for errors and in most cases simply let php catch and handle the exception, where php will use its error related settings (see the previous paragraph above) to control what happens with the actual error information (database statement errors will 'automatically' get displayed/logged the same as php errors.)
    to enable exceptions for errors for the mysqli extension, add the following line of code before the point where you make the database connection -
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);  
  11. mac_gyver's post in PHP MySQL update query not working if not all form fields completed was marked as the answer   
    the main problem with the current code is that it doesn't have any 'working' error handling for the insert query. the error handling you do have for that query is testing if the sql query statement, which is a string, is a true value, which it always will be. instead, use exceptions for database statement error handling and only catch and handle the exception for user recoverable errors, such as when inserting/updating duplicate or out of range user submitted data values. in all other cases, simply let php catch and handle the exception, where php will use its error related settings to control what happens with the actual error information (database statement errors will 'automatically' get displayed/logged the same as php errors.) you would then remove any existing database error handling conditional logic in your code (for the connection and insert query), since it will no longer get execution upon an error.
    if you are familiar with the PDO extension, use it. it is much simpler and more modern than the mysqli extension, especially when dealing with prepared queries, which you should be using, since they provide protection against sql special characters in data values, for all data types, from breaking the sql query syntax.
    code for any page should be laid out in this general order -
    initialization. post method form processing. get method business logic - get/produce data needed to display the page. html document. your code generally follows this, but it has things like two session_start() statements, that needs to be cleaned up.
    the post method form processing should -
    detect if a post method form has been submitted before referencing any of the form data. keep the form data as a set in a php array variable, then operate on elements in this array variable throughout the rest of the code. trim all the input data, mainly so that you can detect if it consists of all white-space characters. validate inputs, storing validation errors in an array using the field name as the array index. after the end of the validation logic, if there are no errors, use the form data. after using the form data, if there are no errors, perform a redirect to the exact same url of the current page to cause a get request for that page. any redirect needs an exit/die statement after it to stop code execution. 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. if there are errors at step #5 or #6 on this list, the code would continue on to display the html document, where you would display any errors and redisplay the form, populating the form field values with any existing data. since there won't be any existing data values the first time the form is displayed, you need to address this at the point of using the values in the form. php's null coalescing operator ?? is a good choice to use here. any external, dynamic, unknown value output in a html context should have htmlentities() applied to it to help prevent cross site scripting. here's a laundry list of addition things for the posted code -
    the php error related settings should be in the php.ini on your system use 'require' for things your code must have for it to work creating a sales order is an administrative activity. you should have a login and user permission system to control access to this operation don't copy variables to other variables for nothing, just use the original variables don't use multiple variables to indicate something when one will work, e.g. orderIDx/orderActivex the session can hold data from different parts of your application. don't completely destroy the session, only unset specific things when needed. since you will be directly testing/using the session variable, instead of copying them to other variables, you won't be destroying or unsetting session variables for the part of the code you have shown. don't blindly loop over external data. hackers can cause 1000's of post variables to be submitted to your code. instead, only operate on expected post entries. you should actually be using a data-driven design, where you have an array that defines the expected fields, their validation, and processing, that you would loop over to dynamically do this operation. don't use variable variables, especially on external data. this allows hackers to set ANY of your program variables to anything they want. don't redirect around on your site, accepting values in the url to control what gets displayed as the result of performing an operation. this opens your site to phishing attacks. if you have a need for using numerical values to indicate which of multiple states something is in, use defined constants with meaningful names, so that anyone reading the code can tell what the values mean in the validation code, setup a unique and helpful error message for each validation error for each input, i.e. don't make the user guess what was wrong with the submitted data if any of the fields/columns must be unique, define them as unique indexes in the database table, then test in the database exception error handling if the query produced a duplicative index error number (1062 if i remember correctly.) for all other error numbers, just re-throw the exception and let php handle it. an empty action="" attribute is actually not valid html5. to cause the form to submit to the same page, leave out the entire action attribute don't put name or id attributes into the markup unless they are used you should validate the resulting web pages at validator.w3.org <option tags don't have name attributes you can put php variables directly into over-all double-quoted strings, without all the extra concatenation dots and quotes. just about every SELECT query should have an ORDER BY ... term so that the rows in the result set are in a desired order don't echo static html. just drop out of php 'mode' when you build and output the <option lists, output the selected attribute for the option that matches the existing form data when you output the checkbox field, you would output the checked attribute if that field is set in the existing form data the point where you are using - echo '0 Results'; won't display anything because it is inside the <select></select> tags. if there are no option choices, you should probably not even output the markup for the entire field, and output the message instead when conditional logic 'failure' code is much shorter then the 'success' code, invert the condition being tested and put the 'failure' code first. this will make your code clearer and cleaner  
  12. mac_gyver's post in Avoid appointment conflict was marked as the answer   
    the following is a 'tricky' example of INSERTing data that satisfies a maximum count of rows -
    $query = "INSERT INTO team_members (team_id, staff_id, stafftype) SELECT -- the following values being SELECTed are the actual data values to insert ?,?,? FROM DUAL -- dual is an allowed dummy table name to satisfy the FROM ... WHERE syntax WHERE (SELECT COUNT(*) FROM team_members WHERE team_id = ? AND stafftype='leader') < 1 -- insert the data if the WHERE (subquery count) < 1 is TRUE"; $stmt = $pdo->prepare($query); $stmt->execute([$team_id, $staff_id, $stafftype, $team_id]); if($stmt->rowcount()) { echo "A leader row was inserted for team_id: $team_id, staff_id: $staff_id<br>"; } else { echo "A leader already exists for team_id: $team_id<br>"; } this example was to insert a maximum of one 'leader' row per team id. you would change it to insert a maximum of two rows per datetime appointment slot.
    because this uses a single query to both get a count of the number of existing rows and insert a new row, it will work correctly for multiple concurrent instances of your script.
  13. mac_gyver's post in Apostrophe Errors was marked as the answer   
    due to things like cross site scripting and phishing attacks, even if this form and form processing code is only accessible to logged in users, the data submitted can be anything, cannot be trusted, and must be used securely in every context (sql, html, mail header, file operation.) a lot of web sites have been taken over due to injected code in values that were 'only being viewed by staff members'.
    the posted code example is - insecure (the current problem), provides a poor user experience (when there are validation errors, which the code doesn't even perform, by putting the form and form processing code on separate pages, requires the user to keep reentering data over and over), is filled with copying of variables to other variables for nothing, and has error handling for the database statement that would only confuse the visitor.
    prepared queries are the simplest, fool-proof way of preventing any sql special characters in a value, a ' in this case, from breaking the sql query syntax. however, the mysqli database extension is overly complicated and inconsistent when dealing with prepared queries. you would want to switch to the much simpler and more modern PDO database extension.
    the form processing code and form should be on the same page. this will reduce the amount of code that must be written, allow any user/validation errors to displayed with the form, and allow previously entered data values to repopulate the form fields so that the user doesn't need to keep reentering data upon an error.
    you should use exceptions for database statement error handling and only catch and handle the exception in your code for user recoverable errors, such as inserting/updating duplicate or out of range user submitted values. in all other cases, simply let php catch and handle the exception,  where php will use its error related settings to control what happens with the actual error information (database statement errors will 'automatically' get displayed/logged the same as php errors) requiring no logic in your code at all.
    for more than about 2-3 form fields, you should use a data-driven design, where you have an array that defines the expected fields, validation steps, and processing, that you would simply loop over using general purpose code, rather then writing out, testing, debugging, and maintaining a bunch of bespoke code for every possible field.
  14. mac_gyver's post in MySQL UPDATE changes all rows instead of WHERE was marked as the answer   
    when i tried your code, $headerData being used when the query is executed is the full 'Battery-0975GJ' value. this is a string, not an integer. you are casting it as an integer in the bind_param("si" usage, resulting in a zero for a value. in sql queries, when one parameter in a comparison is a number, the other parameter is converted to a number as well. you are getting WHERE 0 = 0 which is matching every row.
     
     
  15. mac_gyver's post in I need help with this PHP issues. was marked as the answer   
    if you were doing this for real, where the price can change over time, the pricing would be stored in a related table, associated back to the token rows through the token's id, with a token_id, price, and effective start and effective end datetime columns.
    the point of the id column in this table is to assign a token id (auto-increment integer primary index), that would be stored in any related data table. this is the value that the form would submit for the selected token and would be stored in the usertoken table, not the token name.
    the balance is a derived value. you would not maintain the balance as a single value in a column, but would instead calculate it when needed. to do so, you need an account(ing) table, with a separate row inserted for each deposit/withdrawal that affects the account balance. also, the full name should be stored, using two columns, e.g. first_name, and last_name, so that you can uniquely distinguish between and search for people by name, e.g. is someone Ross Martian or Martian Ross?
    the account(ing) and usertoken table would use the id value from the users table, to related any stored data back to the correct user.
    this table should contain all the who, what, when, where, and why information about the purchase. the who would be the user_id of the buyer. the what would be the token_id, quantity, and purchase price (if you have a separate table for the pricing, you don't need this value). the when would be the datetime of the purchase. the where would only apply if there's a location associated with the purchase. the why would be a status/type value or memo field describing the reason for the purchase.
    this table doesn't need the account number, as that is defined in the users table and is known based on the user id. also, the totalbuy is a derived value that isn't stored. it is calculated when needed using the quantity and the purchase price (or the separately stored price at the datetime of the purchase.)
    the discount amount should be calculated and inserted as a separate row, in a related discount/interest accounting table, related back to the usertoken through the id in the usertoken table.
    you must do this as a single 'atomic' operation, in one query. the way to do this is use the query technique shown in this thread -  https://forums.phpfreaks.com/topic/315532-avoid-appointment-conflict where you have an INSERT ... SELECT query that will only insert a new row in the usertoken table if the where clause calculates if the user's current balance - by summing the user's accounting rows, discount/interest rows, minus the user's existing token purchase amounts, is greater then or equal to the total amount of the submitted purchase.
    and just to clarify, the only two values submitted from the form should be the selected token id and the quantity. everything else should use values that only exist on the server.
     
  16. mac_gyver's post in I want to update an employee profile as an admin but it not update and shows a warning in the placeholder for the unique id was marked as the answer   
    you are using a post method form, followed by an unnecessary redirect, to select which record to edit and then a get method form for updating the data. this is backwards. you should use get inputs to determine what will be displayed on a page and a post method form when performing an action on the server, such as updating the data. also, you can and should do all of this on one page to avoid repetition of code.
    the code for any page should be laid out in this general order -
    initialization post method form processing get method business logic - get/produce data needed to display the page html document when you display the existing records, the edit button should be a get method link with the id as part of the link. when you click one of those links, the resulting code that gets executed would query to get the  existing row of data to populate the form field values, but only if the update form has never been submitted. if the update form has been submitted, you would not execute this query. the way to accomplish this 'interlocking' of the data being edited is to use an internal 'working' array variable to hold this data, then use elements in this array variable through out the rest of the code. inside the post method form processing logic, you would store a trimmed copy of the $_POST form data in this variable. at the point of querying for the initial data, if this variable is empty, you would execute the query.
    here are some issues with and things that will simplify the posted code -
    your login system should only store the user id in the session variable upon successful login, then query on each page request to get any other user information, such as the user's name, permissions. your code should check if the current logged in user is an admin before allowing access to the edit logic. when conditional 'fail' code is much shorter than the 'success' code, if you invert the condition being tested and put the fail code first, it results in clearer, cleaner code. also, since the fail code is a redirect in this case, which must have an exit/die statement to stop php code execution, you can eliminate the else {} part of the conditional test since the redirect/exit/die will stop the execution for a non-logged in user. don't copy variables to other variables for nothing. this is just a waste of typing and introduces errors. don't use multiple names for the same piece of data. whatever the actual meaning of the data is, use that name throughout the code. one such example is the staff_id value being called 'data' and at another point it is a name value. since you will be switching to use a post method form for the update operation, after you detect if a post method form has been submitted, all the form fields (except for unchecked checkbox/radio fields) will be set. there will be no need for a massive list of isset() statements. you should put the database connection code in a separate .php file, then require it when needed. you should not unconditionally echo database errors onto the web page, which will only help hackers when they internationally trigger errors. instead, use exceptions for database statement errors an in most cases let php catch and handle the exception. the exception to this rule is when inserting/updating user submitted data that can result in duplicate or out of range values, which is something that you are doing. in this case, your code should catch the exception, test if the error number is for something that your code is designed to handle, and setup a message letting the user know what was wrong with the data that they submitted. for all other error numbers, just re-throw the exception and let php handle it. the logout operation should use a post method form. any function definitions should either be in the initialization section of code or be in their own .php files that get required in the initialization section of code. your application should not use the root user without any password. instead, create a specific database user with a password with only the  permissions that it needs for you application. the updateRecord function should only have two call-time parameters. an array of the input data and the database connection. the updateRecord should not contain any application specific html markup. this should be handled in the calling code. the function should only return a true or false value to the calling code. don't put external, unknown, dynamic values directly into sql query statements. you must protect against sql special characters in data values from being able to break the sql syntax, which is how sql injection is accomplished. the fool-proof way of doing this is to use prepared queries. since the mysqli extension's prepared query interface is overly complicated and inconsistent, this would be a good time to switch to the more modern and simple PDO database extension. the updateRecord function should not close the database connection. it is not the responsibility of this function to do this, only to update the recorded. the update form should populate the form field values and preselect the option that matches the initial existing data being edited, then populate/preselect using the submitted form data, as described above. any dynamic value that you output on a web page should have htmlentities() applied to it to help prevent cross site scripting. the value attribute for the select/option 1st prompt option should be an empty string. since you are putting the <label></label> tags around the form field they belong with, you don't need the for='...' and matching id='...' attributes. the post method form processing code should -
    detect if a post method form was submitted. keep the form data as a set in an array variable. trim all the input data as at once. after you do item #2 on this list, you can do this with one php statement. validate all the inputs, storing validation errors in an array using the field name as the array index. after the end of all the validation logic, if there are no errors, use the form data. after 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 the page. if you want 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. if there are errors at step #5 or #6 on this list, the code would continue on to display the html document, where you would test for and display any errors, and redisplay the form, repopulating the field values/selected option choices with the values that are in the 'working' array variable holding the submitted form data.
  17. mac_gyver's post in loop multidimensional array was marked as the answer   
    foreach(array_keys($matches[1]) as $key) { echo "SKU number {$matches[1][$key]} costs {$matches[2][$key]}<br>"; }  
  18. mac_gyver's post in PHP Loop: API with max queries was marked as the answer   
    $sku = array( '1234', '5678', '4444', '2222', '9393', '1111', '8689' ); foreach(array_chunk($sku,5) as $chunk) { $qs = '&SKU=' . implode('&SKU=',$chunk); // examine the result echo $qs . '<br>'; }  
  19. mac_gyver's post in about using variables in a query was marked as the answer   
    the main point of using a prepared query, e.g. with place-holders in the sql statement where the data values are to be acted upon, then supply the actual data values when the query is executed, is to prevent any sql special characters in a data value from being able to break the sql query syntax, which is how sql injection is accomplished, by separating the parsing of the sql query syntax from the evaluation of the data values. a secondary point is they provide a performance gain (~5%) in the rare cases when you execute the same query within one instance of your script with different data values, since the sql query statement is only sent to the database server once, where it is parsed and its execution is planned only once.
  20. mac_gyver's post in Php and javascript with mysql copy button was marked as the answer   
    in general, functions should accept input data as call-time parameter(s), so that they can be reused with different input values.
    start by dynamically building the id attribute, incorporating the $row['id'] value (note: you can put php variables directly into an overall double-quoted string without all the extra quotes and concatenation dots) -
    id='c_{$row['id']}' dynamically build the function call with the same value as its call-time parameter -
    <button onclick=\"myFunction('c_{$row['id']}')\">Copy</button> modify the function definition to use the call-time parameter as the id of the element to reference -
    function myFunction(id) { // Get the text field var copyText = document.getElementById(id); .. the rest of the function code is the same  
  21. mac_gyver's post in Mysql question was marked as the answer   
    php variables are not replaced with their value unless the string they are inside of uses initial/final double-quotes. also, when you have just a variable, e.g. the $dbuser and $dbpass, don't put quotes around it/them at all.
    several of the things you have posted should have been producing php errors. do you have php's error_reporting set to E_ALL and display_errors set to ON, preferably in the php.ini on your system, so that php will help you by reporting and displaying ALL the errors it detects?
    the PDO extension is much simpler, more consistent, and more modern than the mysqli extension. if you are just starting out, forget about the mysqli extension.
    when you make the PDO connection, you should name the variable holding the connection as to what it is, such as $pdo. you should also set the character set to match your database tables, set the error mode to use exceptions, set emulated prepared queries to false, and set the default fetch mode to assoc.
    don't bother catching any database exception unless it is for something that the user to your site can recover from, such as when inserting/updating duplicate or out of range data. in all other cases, simply let php catch and handle any database exception, i.e. don't put any try/catch logic in your code.
    you should always list out the columns you are SELECTing in a query and build the sql query statement in a php variable.
    this is obsolete markup. use css instead. you should validate your resulting web pages at validator.w3.org
    don't copy variables to other variables for nothing. this is just a waste of typing. just use the original variables.
    in most cases, there's no need to free result sets, free prepared query handles, or close database connections, since php will destroy these when your script ends.
     
  22. mac_gyver's post in DIfferent class if first row was marked as the answer   
    // before the start of the loop, set a variable to the unique/one-time output you want. $first = 'class="active"'; while($row = mysqli_fetch_array($result)) { // echo that variable at the point where you want the output ?> <li><a id="<?php echo $row["urlName"] ?>Tab" <?=$first?> href="#<?php echo $row["urlName"] ?>Content"><?php echo $row["title"] ?></a></li> <?php // then set that variable to an empty string after the point where you echo it. every pass through the loop after that point will echo an empty string, i.e. nothing will be output. $first = ''; }  
  23. mac_gyver's post in Update Price based on Quantity Selected was marked as the answer   
    <script> const format = (num) => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(num); </script> replace $('#totalPrice').text(totalPrice); with $('#totalPrice').text(format(totalPrice));
  24. mac_gyver's post in Not connecting to MySql database using $CONN in attempting to set up ElementorPro CRUD was marked as the answer   
    you should be learning, developing, and debugging your code/queries on a localhost development system. trying to use public/online hosting is a waste of time, constantly uploading, and making sure there were no upload errors, to see the result of each change. until your code is secure, this opens the possibility of your web hosting getting abused by hackers. also, most cheap shared web hosts disable things like php's error related settings and database error settings that you need in order to get php and your database statements to help you. they also set disk and web server caching so that you won't immediately see the result of changes you make to your code.
    the database hostname on shared hosting is generally not going to be localhost. your web host should have an FAQ section that gives examples of connection credentials. the control panel where you created your database user/password should also list the hostname/ip address to use and any prefix for the username.
    if you can setup php's error related settings, you need to set error_reporting to E_ALL and set display_errors to ON. these should be in the php.ini on your system so that they can be changed at a single point.
    next, you always need error handling for statements that can fail. for database statements that can fail - connection, query, prepare, and execute, the simplest way of adding error handling, without adding logic at each statements, is to use exceptions for errors and in most cases simply let php catch and handle the exception, where php will use its error related settings (see the above paragraph) to control what happens with the actual error information (database statement errors will 'automatically' get displayed/logged the same as php errors.) to set the error mode to exceptions for the mysqli extension, add the following line of code before the point where you make the database connection -
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); lastly, if you are just starting with php/MySql, learn and use the simpler and more modern PDO database extension.
  25. mac_gyver's post in Some Real Beginner's Questions was marked as the answer   
    the code for any php page should be laid out in this general order -
    initialization post method form processing get method business logic - get/produce data needed to display the page html document the code for any particular section can all be in the main file or divided between the main file and any number of separate files that get 'required' when needed. the html document should only contain simple php code, acting like a template engine, that operates on the input data supplied to the html document from the other sections of code OR more simply just use a 3rd party template engine.
     
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.