Jump to content

kicken

Gurus
  • Posts

    4,695
  • Joined

  • Last visited

  • Days Won

    177

Community Answers

  1. kicken's post in Add (sum) currency values was marked as the answer   
    Formatting values should always be a last-step operation.  You want to structure your code so the prices remain as numbers and you can do whatever operations on them you need to do, then only format them right before you display them, for example directly in your template if possible.
    $price1 = 30; $price2 = 74.99; $bundle = $price1 + $price2; //...anything else //When everything is done and you're ready to display echo getMoneyUSD($price1); echo getMoneyUSD($price2); echo getMoneyUSD($price3); Also, you should know that floating point math can lead to issues due to lack of precision.  A common way to avoid these issues is to work with your prices as integers (ie, number of cents) then convert them to decimals as part of the formatting process.  Alternatively, you could find a library for dealing with currency values that handles such issues for you.
     
  2. kicken's post in Just curious to know why was marked as the answer   
    Assuming mysql, Your tables may be using the MyISAM engine which does not support transactions.  You should be using InnoDB unless you have a specific reason not to.
  3. kicken's post in Php Mysql IP Ban error in script was marked as the answer   
    Your file has a invalid character in it that needs to be removed.  Try deleting the line and re-typing it.  Don't copy/paste or you'll copy/paste the character as well.
     
  4. kicken's post in Trouble with Xdebug Breakpoint using Sublime Text was marked as the answer   
    In order to use step debugging, xdebug.mode needs to contain debug.
    If it still does not work after adding that, try setting xdebug.start_with_request to yes.
    I have not used either sublime or that browser extension, so not sure if they need anything special.
     
  5. kicken's post in Inserting multiple values for one user in new column was marked as the answer   
    Sounds like you just want an update query.  For example
    update users_table set reqid=75 where username='joe' If that's not what you want, then you may need to try and explain again differently.
  6. kicken's post in How to get where is the old row in new query? was marked as the answer   
    Before anything else, you need to add an ORDER BY clause to your query so that you can ensure a consistent order of your results.  Without an ORDER BY clause, the database server is allowed to return the rows in whatever order it wants, usually that's just whatever order it finds them in as it scans the indexes/tables.  As you add/remove data that order will change.
    Once you have your results ordered in a specific way, you can count the number of records that come before a specific row by running a query with a where condition of theOrderByColumn <= yourCurrentRowsOrderByColumn.  For example.
    SELECT id,path, subCategoryId FROM `files` WHERE categoryId=5 AND subCategoryId=15 ORDER BY id; SELECT COUNT(*) FROM files WHERE categoryId=5 AND subCategoryId=15 AND id <= 307  
  7. kicken's post in What is it for ReflectionAttribute::IS_INSTANCEOF was marked as the answer   
    Look at the documentation for getAttributes().  There is a flags parameter which is where you use the IS_INSTANCEOF constant.
     
  8. kicken's post in Code doesn't crash but gives no result was marked as the answer   
    Your analyzePage function is not returning a value, so your $analysis variable will be null.  If you have PHP's error reporting turned up all the way, and are on a modern version of PHP, you should be seeing a warning about not being able to use foreach on a null value.
    On an unrelated note:
    This could simply be return $content; There is no need for the check against false there since if it is false, you will just return false.
  9. kicken's post in access to the target of an attribute was marked as the answer   
    This is where the misunderstanding of what attributes are and are for seems to come in.  Attributes apply to the class itself.  The only way to make a connection between a specific instance of a class and that classes attributes is when you use reflection on the instance to look up it's class and associated attributes.  This process only works one way: instance -> class -> attributes.  You cannot go backwards the other way: attribute -> class -> instance. 
     
  10. kicken's post in Is there a correct way to exit JSON? was marked as the answer   
    It's a lot like using relative file paths rather than absolute paths in your PHP code or HTML links. 
    Rather than trying to reference everything with an ID and getElementById, you instead reference elements relative to other elements using things like parentElement, nextElementSibling, previousElementSibling, querySelector, etc.  You can usually reference some parent element (either by ID or a class name) then locate child elements either via their position in the HTML structure or class names.
    Without knowing what your HTML is, I can't provide and specific recommendation.  Here is an example though:
    window.addEventListener('DOMContentLoaded', () => { const list = document.getElementById('option-list'); list.addEventListener('change', (e)=>{ const checkbox=e.target; const description=checkbox.parentElement.nextElementSibling; description.style.display=checkbox.checked?'block':'none'; }); }); Paired with the HTML
    <ul id="option-list"> <li> <label><input type="checkbox"> Test option 1</label> <div class="description">Some description for option 1</div> </li> <li> <label><input type="checkbox"> Test option 2</label> <div class="description">Some description for option 2</div> </li> <li> <label><input type="checkbox"> Test option 3</label> <div class="description">Some description for option 3</div> </li> <li> <label><input type="checkbox"> Test option 4</label> <div class="description">Some description for option 4</div> </li> </ul> The JavaScript code only references the parent list element by and ID and listens for a change event on it (which will be triggered by a change in any child).  When that change event is triggered, the input element that triggered it can be references using e.target.  Looking at the HTML structure, the div that should be shown/hidden is a sibling to the inputs parent, so a reference to it can be obtained by first getting the input parent (parentElement) then it's next sibling(nextElementSibling).
    With this code, you can add as many <li> elements following that structure as you want and they will all work.  No need to generate unique IDs for each and add custom event handlers to each one.
     
     
    For exactly the reason you created this thread, and more.  ID's must be unique, so if you have some repeating structure you need to find some way of generating unique IDs and reference those IDs in your code.  Often times, using class names or other more natural references are better and avoid these issues.
     
  11. kicken's post in Using submit to open a new page in a new window was marked as the answer   
    You can use target on a form tag also.
    <form method="post" target="_blank"> <input type="submit"> </form>  
  12. kicken's post in Book about IIS and PHP? was marked as the answer   
    The server software you use is not that relevant to developing in PHP.  Installing and configuring PHP itself to run will vary based on the server software, but once that is done, your scripts run the same regardless of the server.  I do all my local development work using Apache, but the production site is hosted on IIS.  The PHP code is all the same, there's nothing in it that cares which server software is being used.
    The server configuration required to get PHP installed and running, and to configure specific things needed by the site vary between the two of course.  For example, IIS doesn't understand .htaccess files, it has it's own web.config file for dynamic site configuration settings.  The way the domain and document roots are setup is different as well, but that's general server administration stuff and not PHP specific.  For that information you'd just find IIS or Apache documentation / tutorials.
    If your goal is just to learn PHP, then you'd probably have an easier time just setting up apache since a lot of documentation references it.  If your goal is to learn IIS, then seek out IIS documentation in general rather than IIS+PHP specific stuff.
     
  13. kicken's post in Create session with expirey that updates on each refresh was marked as the answer   
    If you want to change the session cookie parameters, you need to do so before you call session_start(), not after.
  14. kicken's post in Does this javascript code cause stateless or stateful protocol request? was marked as the answer   
    Your JavaScript code doesn't involve a request at all, other than the one to initially load the page which is going to be a standard stateless HTTP request.  The only stateful protocol you would possibly end up using in JavaScript code is a WebSocket.  The rest of the web revolves around stateless HTTP requests.
    That blog post has less to do with HTTP and more to do with applications.  HTTP is stateless, but most web applications are not as they rely upon session data to track who is logged in or other details.  That session data makes the application as a whole stateful even if the individual HTTP requests are not.
     
  15. kicken's post in Server Resets while page is loading was marked as the answer   
    IIS has various timeout settings.  If this is a large import, you shouldn't be doing it through a web interface like phpMyAdmin, long running requests don't usually work out well.  You'd be better off using the command line tools to do the import or a tool like MySQL Workbench that can connect directly to the database and run the import.
     
  16. kicken's post in Php Mysql 2 if statements for one hide echo was marked as the answer   
    The syntax of an if statement looks like this:
    if (some condition){ //do stuff } The some condition part could be a single comparison, or multiple comparisons joined with logical operators.  Note though, how there needs to be a set of parenthesis surrounding the entire condition.   Now, look at your attempt:
    if (strpos($row["message"], 'And Click') == true) && ($viewspec_pref == "no") { You have your two conditions combined with the logical AND operator.  What you're missing through, is the parenthesis that surrounds the entire combined condition.  Instead, you put parenthesis around the individual conditions (which is ok, but unnecessary).  Add the required parenthesis around the entire condition and you'll have something that is syntactically valid. 
    It is a potential issue. The solution, which was never really pointed out, is that you need to strictly compare against false to determine if a match was found or not.  Using a loose comparison against true will fail if your message starts with the target string (since strpos would return zero, and zero is falsely).
    if (strpos($row["message"], 'And Click') !== false && $viewspec_pref === "no") { It can generally be worth getting in the habit of using the strict comparison (identical) operators whenever possible, as it helps avoid such surprise outcomes.
    If you are using PHP 8.0 or better, you can avoid this whole problem by using str_contains instead.
  17. kicken's post in Loading PDF files into a sql database was marked as the answer   
    Try
    $stmt->bindParam(':fileContent', $fileContent, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY);  
  18. kicken's post in php class autoload question was marked as the answer   
    There are no internals of spl_autoload_register with regards to the locating and loading of a class.  All the details of how that is done is up to the function you provide.  All spl_autoload_register does is add your function to a list of functions that get called when an unknown class is referenced.  Your function gets the fully qualified name of the class and has to use that to define that class, typically by converting the name to a file location and including that file.
    Your example essentially just uses the class name as-is as a file path and attempts to include that file.  Since your class is defined as Hello then you get a filename of Hello.class.php with a capital H.  Your actual filename however seems to be hello.class.php with a lower-case H.  On a case-insensitive filesystem such as windows' ntfs, this would be fine and the file would be loaded.  On a case-sensitive filesystem such as linux ext4, this is a problem and the file will fail to load.
    As mentioned, typically one would just use composer to handle class autoloading rather than defining your own function.  Combine it with the PSR-4 standard (and ensure you get your case correct) and you mostly don't have to think about it at all.
  19. kicken's post in Centering the popup form was marked as the answer   
    Been a long time since I used a positioned popup window.  Had to check the docs for the right options.
    You can center the popup on the screen by setting the top / left options.  These control the top-left corner of the window, so to get it truly center you have to calculate the right offset.  There's a standard formula for this.
    centerPoint = (sizeOfContainer - sizeOfThing) / 2 For this case, your sizeOfContainer is the screen width/height and the sizeOfThing are your popup window's width/height.  Run that formula for each to get your top/left values and set them in the window options.
    const popupWidth = 400, popupHeight = 800; let top = (window.screen.height - popupHeight)/2; let left = (window.screen.width - popupWidth)/2; const win = window.open('', 'formpopup', 'width='+popupWidth+',height='+popupHeight+',resizable,scrollbars,top='+top+',left='+left); The final result may be slightly off (mostly in the height axis) due to the window UI elements since they are not part the calculation.  The width/height you specify is for the content area of the window, the UI elements are added on top of that.  If the slight offset bugs you, you can fix it after opening the window by re-calculating the offset using the window's outerWidth and outerHeight values for sizeOfThing, then using it's moveTo function to re-position it.
    top = (window.screen.height - win.outerHeight)/2; left = (window.screen.width - win.outerWidth)/2; win.moveTo(left, top); That may create a noticeable jump after the window opens though.
  20. kicken's post in variable functions was marked as the answer   
    PHP allows extra values to be passed to a function.  You can use func_get_args to obtain these values within the function and do something with them.  This is the original way of creating a variable-length argument function.
     
  21. kicken's post in Why does window.load function triggers "click" event of elements? was marked as the answer   
    In that line, you are not assigning the toggleBtn function as an on-click event handler.  You are executing that function now and assigning whatever value it returns (which is nothing) as your on-click handler.
    You need to wrap it an anonymous function which is passed to addEventListener as the click handler.
    item.addEventListener('click', function(){ toggleBtn(item,index,arr); }, false)  
  22. kicken's post in Why "sometimes" changing display property of div cause my "hide" script to fall into infitinite repetition state ? was marked as the answer   
    There is a concept in design/engineering called Hysteresis.  In a nut shell, you don't define hard cut-off points and instead define a range, or introduce a delay of some sort.
    So instead of having your code hide the menus when the container is <50 px from the top and show them when 50px or more from the top, you instead set it up such as:
    If container is <50 px from the top, hide the menus If container is >150px from the top, show the menus. If the container is between 50px and 150px from the top, just maintain whatever the current state is. The range can be fixed like the example, or dynamic by calculating the menu heights.  You just need the range to be large enough that toggling the visibility of the menus doesn't cross both boundaries.
     
     
  23. kicken's post in Query selector problem was marked as the answer   
    querySelectorAll returns a NodeList, which does not have an addEventListener method.  Assigning an event handler to a collection of elements is a jQuery thing.  In plain JavaScript, you have to loop over the elements in the collection and assign the event handler to each one individually, or attach it to a common parent element.
    document.querySelectorAll("p").forEach((e) => { e.addEventListener('click', fn); });  
  24. kicken's post in javascript, calling php and getting a return was marked as the answer   
    This bit of code is very antiquated.  For new development, unless you have some need to support ancient IE systems, you should either just use new XMLHttpRequest unconditionally, or preferably, use fetch(). 
    Part of your issue is also not understanding what this means in the code I think.  this refers to whatever object a function is attached to.  In your onload function, this will refer to your xmlhttp object.  Outside of that function, this would refer to something else, so this.responseText outside the function is not the same as this.responseText inside the function.  Outside the function, you'd use xmlhttp.responseText.
    My suggestion is you get rid of this code, and write your code using the modern fetch() api.  That would look something like this:
    fetch('save_pool_history.php?action=select_past').then((response)=>{ if (!response.ok){ throw new Error('Invalid Response'); } return response.text(); }).then((text)=>{ alert(text); }).catch((error)=>{ alert('Error fetching response.'); });  
  25. kicken's post in email acknowledgement - follow-up was marked as the answer   
    Did you enable remote content in your email client?  Most block it by default as far as I know.
×
×
  • 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.