Jump to content

gizmola

Administrators
  • Posts

    5,970
  • Joined

  • Last visited

  • Days Won

    147

Community Answers

  1. gizmola's post in Error message copying data from one database to another on the same server was marked as the answer   
    You are clearly new to doing queries with the php mysqli extension.
    First of all, why are you including extraneous parens and punctuation in your query?
     
    What you are doing:
    $sql= "select * from cic_remus.contacts where (id='$id');"; What it should be:
    $sql = "select * from cic_remus.contacts where id=$id"; Your problem is likely a logic issue as Kicken has pointed out, but you should also address the underlying issue for debugging purposes:
    This is telling you that you have an uncaught exception, so try surround the code with a try..catch block for that and then display the actual exception message and query next time you do this.
    try{ // sql query code } catch(Exception $e) { echo "Error: " . $e->getMessage(); }  
    I'm not sure why you are doing what you are doing, when instead you can just do a query:
    INSERT INTO cic_kenobi.contacts AS select * from cic_remus.contacts ON DUPLICATE KEY IGNORE If the tables don't exactly match (you can craft the individual values statement in the same way you already have been).  You can run this from PHP but unless you are doing this frequently, having it scripted within php doesn't have a lot of value to it.
  2. gizmola's post in how to add extension in php? was marked as the answer   
    I don't know what you found on SO, but it's unrelated to the intl extension.
    What operating system are you running? What version of php? How is your development environment configured? Are you using Docker?  
    Note: The library you are trying to use states that it is "depreciated"  (sic).  It was also forked by the originator to a different repo, with the intention of passing it on to other maintainers.
    Since you are using Laravel, this one might be a better fit for your project:  https://github.com/TechTailor/Laravel-Binance-Api
    It states it is still in alpha, but depending on what you intend to do it might be a better fit for you.
  3. gizmola's post in Meta data programmatically was marked as the answer   
    Search engines just look at the final http response data.  They have no visibility into the internals of how a page is rendered.
    There is no problem doing what you want to do, and in fact many cms's, forums and frameworks do this exact thing.
    Just to be clear, meta tag keywords are ignored by google, so you may or may not want to include those in your page rendering.
  4. gizmola's post in Adding a count to a basic player with mysql and php was marked as the answer   
    Yes, so implementing kicken's suggestion, this should work probably:
    $('audio').on("play", function(){ let requestSent = [] return function(){ let a_id = $(this).attr("id") if (requestSent.includes(a_id)) { return; } requestSent.push(a_id) $.ajax({ url: "count-play.php?id=" + a_id , success: function(result){ $("."+ a_id + "count").html(result) } }); }; }()); Hopefully you understand what this code does, which makes use of some tricky javascript concepts, namely:
    Javascript closure An IFFE
  5. gizmola's post in PHP coded button was marked as the answer   
    There's a lot to work through here, so I'll start with this:
    With CSS, always start with more general rules, then more specific ones.  You have multiple embedded style blocks here, and I'm not sure why, but your general rules were added after the specific ones Keep in mind that styles "cascade" per the name. You don't need to re-declare all the attributes for a modification.  Just use a modification class Many popular css frameworks like tailwind depend on this idea   Getting familiar with a naming convention for css like BEM will help you create clear and logical css class names and avoid pitfalls and making your css inconsistent spaghetti It also will help you keep things clear.  Use camel case for your PHP variables, and for class naming and general code formatting and style start with PSR-1 and perhaps graduate to PSR-12 It might not seem that important to you starting out, but it will help you get the most out of whatever editor/IDE you are using Most people are using either PHPStorm (the choice of most pro's) or Visual Studio code with the Inteliphense plugin installed If you go with vscode/Inteliphense make sure to read the installation instructions carefully and disable the built in plugin as directed Take a look at my changes to your css and html markup to see how I implemented these ideas on your code You rarely will want or need to use css id rules.   ID's are reserved for a single instance on an page.  For buttons, you are typically re-using those styles throughout the page, so use css classes for those and not id's Most css pros rarely/never use #name css styles.  If this is tutorial type stuff, might tell you something about the freshness of the tutorial PHP code runs on/in the PHP server.  It does not run in the browser like javascript code that is included or embedded in the html page. In other words, your PHP code will be run in response to a request, and returned immediately. You can intermix html and PHP blocks inside a php script, and that will work fine, but the PHP code needs to be in a PHP block, which starts with <?php  As you should be able to see here, you have commented out all the PHP code you wrote using html comments.  Thus none of that is going to run. There is an alternate syntax that can be used to make everything look a bit cleaner if you plan to do a lot of intermixing You can look up those options in the PHP manual.  It allows shorthand for echo, and if - then -else type constructs and other PHP loop For superglobal array variable or array keys (or any other variable that may or may not exist) you want to check before blindly trying to utilize it.  There are various language helpers that you can use to get around the situation where a variable doesn't exist. isset empty() function null coalescing operator Take care with PHP blocks inside if-then or if-then-else constructs.  In general, it's a good idea to always make sure you have a block { ... } to handle each case.   Your blocks don't look correct. Try not to chain if-then else, when instead you can use multiple if blocks.  The code is easier to read and update in most cases.    
    The issue with the code presented is that you have buttons but no form, so this invokes a lot of confusing default behavior and questions you might want to ask yourself like:
    Why/where is the form submitted? What type of submission is it? For example, if the type of submission is not a POST, can you expect $_POST variables to exist?  
    I don't address these questions for you, but I expect you will need to figure them out soon.
     
    Here's some modifications to your code illustrating these thoughts:
    <meta charset="utf-8"> <title>Work intergrated learning</title> <style> body { font-size: 30px; } p { font-size: x-large; } .btn { padding: 10px; font-size: 20px; border-radius: 10px; font-weight: bolder; transition: background-color 2s ease Os; cursor: pointer; } .btn--submit { background-color: red; } .btn--submit:hover { background-color: green; } .btn--cancel { background-color: yellow; } .btn--cancel:hover{ background-color: orange; } </style> Rest of code...
    <p>Creating a button</p> <br> <?php if (isset($_POST['btn-atc'])){ echo 'You have added an item to your shopping chart'; } ?> <input type="submit" name="btn-atc" value="Add to Cart"> <?php $btnSubmit = isset($_POST['btn-submit']); if ($btnSubmit) { echo 'Your query has been successfully submited, our consultant will get in touch with you as soon as possible'; } $btnCancel = isset($_POST['btn-cancel']); if $btnCancel { echo 'You have cancelled your query.'; } ?> <input type="submit" name="btn-submit" class="btn btn--submit" value="Submit query"><br> <input type="submit" name="btn-cancel" class="btn btn--cancel" value="Cancel">  
  6. gizmola's post in how to properly store an ip address? was marked as the answer   
    I'm guessing something like this might work for you (assuming you have a reverse proxy or load balancer).
     
    protected function getClientIP() { // This assumes a classic AWS Load Balancer is proxying if (filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) && !filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); return $ip[0]; } else { return $_SERVER['REMOTE_ADDR']; } }  
  7. gizmola's post in How do I think about recursion? was marked as the answer   
    I should probably add that the secret to determining if recursion allows for something elegant, is to determine if you can reduce the problem down to a discrete examination.  In the case of my solution, the insight I depend upon is that I only need to check the outer 2 letter of the string in order to determine if it *might* be a palindrome. 
    Another solution using this insight could also be coded using map and reduce. 
    It also needs to be said that the overhead of recursion means that it is almost never employed, although there are some problems involving nested arrays where I see people using it in PHP.  
  8. gizmola's post in [docker] error_log() not work was marked as the answer   
    The PHP process may not be able to write to the /var/log directory.  Assuming it's the apache user that php is running as in this case.  Connect to the container and check out the perms for /var/log.  
  9. gizmola's post in How to Push an Empty Array into an Object was marked as the answer   
    And everything I wrote previously still applies.
    let json_array = {} json_array.excludes = [] // Use array method json_array.excludes.push("a") json_array.excludes.push("b") //array syntax json_array["excludes"].push("c") console.log(json_array)  
    I Updated the codepen as well with this example code.
  10. gizmola's post in Wordpress cross-plugin refering was marked as the answer   
    My educated guess is that requinix is right.   I also think the code snippets reflect that the order object should be available in plugin2 via $this->object.
    So I would suggest you try adding this code to plugin2
    $this->placeholders['{order_service_time}'] = get_post_meta( $this->object->get_id(), '_wfs_service_time', true);
  11. gizmola's post in using array_diff on 2 arrays was marked as the answer   
    He literally gave you code that works, only missing a semicolon:
    $result = array_udiff($table, $newdata, fn($a, $b) => $a <=> $b); var_dump($result); If you are familiar with Javascript ES6, it is a similar type of anonymous function shorthand, equivalent to this:
    $result = array_udiff($table, $newdata, function($a, $b) { return $a <=> $b; }); You need to have a current supported PHP version ( >= 7.4) although the syntax I showed works with any version 7.x or >
    The "arrow function" version was introduced with php 7.4
  12. gizmola's post in When user tries to download .iso, tar.gz, or .deb from my website php is opening the file instead of downloading it was marked as the answer   
    One pro tip:
    Never have a php end tag (ie. ?> ) in your scripts.  It is not needed, and can lead to bugs like this  remove all php end tags whenever they are the last thing in a .php file.
    You can start with looking at PSR-1, and perhaps graduate to PSR-12 if you are looking for some standards to help guide you.
  13. gizmola's post in Cant find the old thread about wrapper/container (CSS2-3). was marked as the answer   
    I don't have any specific recollection of such a thing, but a lot of things have changed in the css world, most notably the standardization of flexbox and grid that make older techniques and tricks of css layout obsolete.  You just don't need those things anymore when flexbox or grid can take care of your layout needs with simple, consistent and easy to understand syntax.  
    There was a time when you needed to know the ins and outs of floats and clear fix, and other arcane tricks of css, but that's basically obsolete knowledge.  People also use to use tables inside tables inside tables to get their "pixel perfect" layouts, but that also has given way to a focus on creating layouts that adapt from desktop to mobile.  
     
    This guy (Kevin Powell) has become well known in the css/web design world, and he really knows his stuff.  This video covers flexbox.  If you work through the examples with him, you will learn what you need.  He also has a corresponding Grid video.
     
    If you want something more interactive, lots of people love Scrimba, and in particular Per Borgen, who is one of the Scrimba founders.  He happens to have a free scrimba course covering grid and flexbox, so that is another way you can learn flexbox, if you want something more interactive.  The free Scrimba Grid/Flexbox course is here:   https://scrimba.com/learn/cssgrid
     
     
  14. gizmola's post in How to override trait methods from another trait? was marked as the answer   
    In the PHP manual section Traits section.
    You have 2 options:
    Alias the conflicting method so it doesn't conflict Specify an "insteadof" method statement in the use section of the class
  15. gizmola's post in PHP Variable Variables & Loops with Forms was marked as the answer   
    No worries - we all agree on using PDO so that is a good investment of your time.
    If you want to goto a new page that just has the signup form, then have all the buttons in the game list inside anchor tags.  Then you can just pass the game_name as a url parameter to the page that generates the form.  The signup page can just set the hidden game attribute using the $_GET parameter.
    I personally would opt for the usability of not having a separate signup form, but if it's simpler for you to go from a->b->c and get things working that way, do that then.  It makes the javascript event stuff simpler, although you will definitely need to learn that sooner than later.  I like Scrimba as a platform to learn html/css/javascript concepts, although there are many other freemium platforms.  Freecodecamp also does a good job.
    Simpler solution for you, again rendered buttons inside your foreach loop that lists the games (ie. one button per game listed):
    echo "<a href='signup.php?game_name=\"{$game['game_name']}\"'><button class='btn_game_signup'>Signup for this game</button></a>"; Clicking on the signup page will send a GET request to your signup.php script, which will include the $_GET parameter of 'game_name'.
    Then you just set the hidden form attribute of that page in your signup.php script to the value of $_GET['game_name'].
  16. gizmola's post in PHP+MySQL Unique Article Styling was marked as the answer   
    Yes there is a way to do this, but it involves a solid foundational understanding of relational database design concepts and how to write code.  It would be a significant amount of work for a professional programmer.  An alternative to reinventing the wheel from scratch would be to use a php based CMS like Drupal or Bolt  These projects start you out with a lot of functionality and systems that already have templating, much of which can be tweaked without programming.  They also have "taxonomies" which are extensible.  You can utilize existing templates to learn how templating works, and how to customize them without already being an advanced developer.
    Not to sound pessimistic here, but creating a blog database is not difficult at all, for something simple, but you still need to know what you are doing.  With that said, even though it might be fairly simple to do so, providing you a custom CMS database structure and instructions on how to create different templates against it is the topic of many an article, book and online course.   If you have a better idea of what approach you might take, people can provide you better advice.
  17. gizmola's post in Widespread Exploitation of Unauthenticated RCE in Apache Log4j (CVE-2021-44228) was marked as the answer   
    To be absolutely clear:  The Apache HTTP server that is commonly used in the AMP,LAMP, MAMP,WAMP stack, is not java based, does not integrate or use any java components, and is not at risk.
    This is a common enough misconception, in regards to Apache vs the Apache Software Foundation.
    The Apache webserver is one of the oldest Free Open Source web servers.  For the record it is written in c.  
    The original core contributors to the Apache HTTPD server, went on to create the Apache Software Foundation(ASF), which was incorporated as a non-profit to support the continued development of FOSS software.  The ASF also authored their own License, that is comparable and competes with the GPL and MIT licenses often used for FOSS.
    Over the years, the ASF has sponsored and brought many different types of software under their umbrella.  These projects benefit from funding and support services provided to them by the ASF.  At present there are something like 180+ individual software projects under the ASF umbrella.  Here is a list by programming language.
    Apache is a big player in the Java development space, with many important tools and java based projects under their umbrella.  Log4j is just one of these projects, but it is often integrated into other java based software and systems via their java logging project.  
    Here's one quote to help understand the potential scope of the problem:
    Anyone running an Enterprise or Java based system is a potential target, but there are also many pieces of java based software that are used by companies for the services they provide.
    For example, note the mention above of "Solr" which is a popular full text indexing engine that many sites who aren't otherwise java based, may use.  Apache also provides the Lucene engine, which is also Java based.  Basically if you are running any sort of java based software server, there is a good chance that the log4j vulnerability is a concern.  
    For any company with sysadmin/devops/developers with a degree of competency, the log4j exploit vector can be quickly and easily closed using several techniques that vary by log4j version and environment.  The problem is that there are many packages of java based software like Lucene & Solr, that the users may not realize are java based.  They may come with a packaged JRE, or be running via an independently installed JVM.
    The actual exploit requires crafted input that gets logged containing instructions which trigger java JNDI to download and run remote code.  So it's a "remote code exploit". 
    If a server with a vulnerable installation or version of log4j doesn't have some sort of publically available listener, there isn't a vector for exploitation.  For example, depending on the integration, your Solr or Lucene engine might not be at risk.  It could depend on how or what you are indexing, and where the data being indexed comes from.
    Many people are running java based editors like Eclipse or Netbeans, or any of the Jetbrains editors, in particular the very popular PHPStorm.  What does Jetbrains have to say about this?  https://blog.jetbrains.com/blog/2021/12/13/log4j-vulnerability-and-jetbrains-products-and-services/
    I hope this helps clarify some things for people.
  18. gizmola's post in Cookies and checkbox was marked as the answer   
    Yes, although again the UI is incorrect.  Checkboxes are not mutually exclusive.  So you are just doing this UI in the wrong way.  Your form code is also wrong. 
    You have a label that is hardwired to dark, yet you have variables toggling the value from light to dark.  When a form is rendered, it should always be checked, because you are using the checkbox to toggle from light to dark.   This means that a value for the checkbox will never be set in the way you using this.  A newly rendered form will always have a value (light or dark) and will be checked.  Once you uncheck it, you'll submit the form, and the checkbox will not be passed.
    However, to your question, you have 2 choices:
    Write a little js that checks the check/uncheck state and sets a hidden element, which you use on submit Just have php check for isset() or use array_key_exists.  If ! isset() then it was unchecked.  You want to check the request method to make sure the form was actually posted. Not that I'd advise this, but in this case, and again you have to be logical and clear, if the form is submitted, then you are looking to toggle the value.  
    <php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $mode = empty($_COOKIE['mode']) ? 'Light' : $_COOKIE['mode']; //Toggle it $mode = ($mode == 'Light') ? 'Dark' : 'Light'; setCookie('mode', $mode); } else { $mode = empty($_COOKIE['mode']) ? 'Light' : $_COOKIE['mode']; setCookie('mode', $mode); } // Now can use $mode to render ?> <input type="checkbox" onChange="this.form.submit()" value="<?= $mode ?>" name="mode" checked> <label for="mode"><?php echo "$mode Mode"; ?><label><br>  
    Again when you think about it, the actual value of the checkbox is irrelevant as you are really going to toggle the cookie value on any submit.
     
    The other option is to use some js.  Probably what I would do is use a hidden field, so that you could rely on the submission, but then when you have a cookie you are also relying on, this whole scheme makes less sense
     
    Something like this could work:
    <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $mode = empty($_COOKIE['mode']) ? 'Light' : $_COOKIE['mode']; //Toggle it $mode = ($mode == 'Light') ? 'Dark' : 'Light'; setCookie('mode', $mode); } else { $mode = empty($_COOKIE['mode']) ? 'Light' : $_COOKIE['mode']; setCookie('mode', $mode); } ?> <!DOCTYPE html> <html lang="en"> <head> <title>Form Test</title> <script type="text/javascript"> function toggleMode() { let cb = document.getElementById("cbmode"); let newMode = document.getElementById("new_mode"); newMode.value = (cb.value == "Light") ? "Dark" : "Light"; console.log(newMode.value); document.getElementById("modeForm").submit(); } </script> </head> <body> <form id="modeForm" method="post"> <input type="checkbox" onChange="toggleMode()" value="<?= $mode ?>" id="cbmode" name="cbmode" checked> <label for="cbmode"><?php echo "$mode mode"; ?></label> <input id="new_mode" type="hidden" value="<?= $mode ?>"> </form> </body> </html>  
     
  19. gizmola's post in Only one select statment instead of two was marked as the answer   
    There is no way to combine the queries,  other than to union them, and that has essentially no significant value to you.  You can write the count query in a slightly more compact manner if you like:
    $total_recs = $conn->query("SELECT count(*) FROM table1")->fetchColumn(); Your pagination limit variables should use bind variables:
    // You'll set your $limit and offset variables from your pagination calculation $res = $conn->prepare("SELECT * FROM users LIMIT ?,?"); $res->execute([$limit,$offset]); $data = $res->fetchAll();  
  20. gizmola's post in No data supplied for parameters in prepared statement was marked as the answer   
    Obviously if you don't have all the data required for the insert, you are going to get an error. One issue that you have made for yourself unnecessarily is:
     
    $user_id=""; $date_created = date( 'Y-m-d H:i:s' ); $date_edited =""; So i'm going to assume that you have an auto_increment for user_id, and date_edited can be null, and since this is a new row you want that to be NULL on insert.

    In this case, you should not be passing values for these. MySQL figures out how to auto_increment, and it makes no sense to pass a NULL date string for a date parameter that you will never set in this context.


    Change the insert so that those are not included:
     
    $stmt = $connection->prepare("INSERT INTO users values(?,?,?,?,?,?)"); $stmt->bind_param("s,s,s,s,s,s", $firstname, $lastname, $username, $hashed_password, $date_created, $status_id);
  21. gizmola's post in Call variable from another function in class was marked as the answer   
    When you define your class, just have properties that store the values you need to ingest from the constructor. Typically you want these properties to be private or protected, so scope them accordingly.
     
     
     

    class Client { private $currentAccount = 0; private $numberOfAccounts = 0; public function __construct($start = []) { //code $this->currentAccount = $currentAccount; //more code $this->numberOfAccounts = $numberOfAccounts; } } It looks like you would benefit from a quick read through the PHP manual section that covers classes and OOP
  22. gizmola's post in Importing an .xlsx file to a MySQL Database by using phpMyAdmin was marked as the answer   
    You can certainly convert it from Excel to csv easily enough, but you need csv to import, so if you can have that instead it saves you some complications.  The important thing with csv is that your string columns need to be surrounded by double quotes so that commas inside a string don't confuse the parsing. This also necessitates that if you have double quotes in the string, the double quotes have to be doubled in order to escape them.
     
    Excel export to csv should do this for you, so ultimately it's up to you if the excel has value outside of the import, or if getting a .csv version is more trouble than it's worth.
  23. gizmola's post in Always Incorrect Credentials when logging in was marked as the answer   
    I'm afraid you need to actual read/debug/trace the login code in order to understand why it works with the original table and not yours, but at least you have pinpointed a logical place to start.
  24. gizmola's post in set partial text color via javascript was marked as the answer   
    You can't just randomly color a piece of text. What you can do however, is put a span around that section, and style the span.
  25. gizmola's post in Real time order confirmation was marked as the answer   
    There aren't any generic examples out there to look at.  The closest thing I could suggest to you would be to look at the php ecommerce projects like Magento, Opencart and WooCommerce (for Wordpress) and even perhaps the API documentation for Shopify.
     
    It depends 100% on a companies specific payment processing & fulfillment systems.  
     
    In the US, there is consumer law that regulates things like this, in terms of consumer goods and when you are actually allowed to charge someone for a product, but even if we ignore that, the simple fact is that companies often have fulfillment and accounting systems that need to be integrated with, or there is no reason for a system to wait.  What is it waiting for?
     
    -Was there inventory available, and could that inventory be reserved?
    -Did the payment go through
    -Alert the fulfillment system that the order was successful, so that the order can be fulfilled
     
    In other words, there is no generic solution to the problem anyone can point you to.  
×
×
  • 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.