Jump to content

maxxd

Gurus
  • Posts

    1,414
  • Joined

  • Last visited

  • Days Won

    44

Community Answers

  1. maxxd's post in Function if comparision outputting false value incorrectly. was marked as the answer   
    I'm pretty sure I don't understand the issue you're having, but right off the top I see this. This is your function definition:
    function getItemsForQuote($itemType, $currency, $qty = null, $startDate = null, $endDate = null, $itemId = null, $notes = null) and this is what you're calling:
    getItemsForQuote($item['itemType'], $item['quoteCurrency'], $item['quantity'], $item['itemId']); You're passing the itemId as the startDate parameter.
  2. maxxd's post in Quotes not quite right! was marked as the answer   
    This is one of the major problems with echoing html from within php - your quotation marks are getting lost/confused. If you have to do this, remember using single quotes is perfectly appropriate for an echo statement in php even though it won't interpolate variables. In your case, this is fine as you're using concatenation. Try this:
    echo '<option value="'.$myrow['cats'].'">'.$myrow['cats'].'</option>'; This way it's easier to see that there are quotes around the option value so you know that spaces in the value won't break the entire thing (which is what's happening to you now).
    It's also a best practice in html to use double quotes for attribute values, so that's cool too. I made the quotes around the array indexes single quotes; I'm not entirely sure that's best practice for php but it's what I've seen most often and what I personally prefer, so...
  3. maxxd's post in PHP Database Class was marked as the answer   
    Yes, using globals is frowned upon. The reason for this is the lack of any real accountability or pinpointing modification points - if the variable is global, it can be changed literally anywhere and this can lead to days of hunt and seek debugging. The current basic pattern is to either instantiate a concrete instance of the database object and pass it to the other objects that require a database connection or setting up a dependency injection pattern/system, but that's a whole extra level of difficulty.
    Extending a class is, for the most part, perfectly safe and fine. Now, the presiding opinion is to prefer composition over inheritance which means most modern advice you'll see and read is that you should - as stated above - either use dependency injection or pass an object into the constructor. There's more controversy in that most people apparently have an issue with singletons, but if you always need the same database connection you'll probably want a singleton object that you pass into the constructor methods of any class that needs it.
    You pass an object to a constructor method in a series of `new` statements. Any time you write, for instance:
    $db = new DatabaseObject(); you're calling the __construct() method of the DatabaseObject class. So, hopefully this'll help a bit:
    <?php class DatabaseObject{ private $pdo; public function __construct(){ $this->pdo = new PDO('connection_string', 'username', 'password'); $this->pdo->setAttribute(PDO::WHATEVER); } public function getDatabaseObject(){ return $this->pdo; } } class Statements{ private $pdo; public function __construct(DatabaseObject $dbo){ $this->pdo = $pdo; } } $pdo = new DatabaseObject(); $stmtnt = new Statements($pdo->getDatabaseObject()); A few additional things:
    You can't access a private variable from anywhere other than the class that defines that variable, even if you're in a child class - in that case you'll want to use protected. Also, in your Database class constructor, you're missing `$this->` on your first line. $this->pdo is a different thing than just $pdo within a class or object.
    Long story short, there's really no one "way" to do things - best practices adapt and change as we all learn and grow as programmers. Best bet is to do the research you're already doing, really take in and understand the information and opinions in that research, and apply that understanding to the problem you're trying to solve - but remember you (or worse, someone else) will always have to revisit the code you're currently writing later on. Don't make it harder on that person as much as you can.
  4. maxxd's post in Images side by side in a grid was marked as the answer   
    You'll need to build an inner div, place it in the middle, column. Set the inner div to grid and style from there.
    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Testing Grid</title> <style> *{ margin: 0; padding: 0; } body{ display: flex; justify-content: center; align-content: center; background: teal; } .outer-container{ background: lightcoral; margin: 0 auto; display: grid; grid-template-columns: 100px 1fr 100px; gap: 10px; justify-items: center; align-items: center; } .inner-container{ background: yellow; grid-column: 2 / 3; display: grid; grid-template-columns: repeat(2, 50%); grid-template-rows: auto; gap: 20px; } .block{ background-color: blue; padding: 20px; } </style> </head> <body> <section class="outer-container"> <div class="inner-container"> <div class="block"><img src="http://fpoimg.com/300x250?text=Preview" alt=""></div> <div class="block"><img src="http://fpoimg.com/300x250?text=Preview" alt=""></div> <div class="block"><img src="http://fpoimg.com/300x250?text=Preview" alt=""></div> <div class="block"><img src="http://fpoimg.com/300x250?text=Preview" alt=""></div> </div> </section> </body> </html> Pardon the eye-searing colors; I like to be able to see what I'm doing...
    Your mileage may vary with the widths you're using - I'm testing on a surface tablet so the screen is smaller.
  5. maxxd's post in Anything other than simple class inheritance escapes me. was marked as the answer   
    Sounds like you're looking at a facade pattern? Or maybe composite or adapter depending on how you want to use the objects.
  6. maxxd's post in Displaying an Alertbox from PHP Controller class was marked as the answer   
    This is typically called a toast notification. For instance, if you happen to use Laravel you'd install toastr as a dependency in pacakge.json:
    "dependencies": { "toastr": "^2.1.4" } Create a toast component or partial:
    <script> @if(Session::has('message')) window.toastr.success("{{ session('message') }}"); @endif @if(Session::has('error')) window.toastr.error("{{ session('error') }}"); @endif @if(Session::has('info')) toastr.info("{{ session('info') }}"); @endif @if(Session::has('warning')) window.toastr.warning("{{ session('warning') }}"); @endif </script> Include that component/partial in your main template file:
    @include('components.toast') Finally, set the message in $_SESSION like so:
    return Response::redirect('/dashboard')->with('message', 'Data Saved!'); Obviously if you're not using Laravel you'll have to do some digging but hopefully that's a decent starting point.
  7. maxxd's post in Template System was marked as the answer   
    We don't know what the rest of your code looks like, so it's difficult to say what's actually happening.
    My biggest question is is there a reason you're not using one of the many existing PHP template engines? Personally, I'm partial to Twig when not in Laravel land.
  8. maxxd's post in disfunctional while loop was marked as the answer   
    A more efficient way is to only select the 8 rows you're looking for instead of selecting the entire table.
  9. maxxd's post in Funky parameter activity was marked as the answer   
    In the commented out version, $column is between $where and $rule. So, when you use the second block of code on the commented-out version of get(), 'OREDER BY RAND()' becomes $column and $rule is blank.
  10. maxxd's post in PHP Error - unparenthesized issue was marked as the answer   
    PHP 8 requires parentheses when using nested ternary operations - https://lindevs.com/nested-ternary-operators-requires-explicit-parentheses-in-php-8-0/.
  11. maxxd's post in Calling an API and Testing within PHP (noobie help needed) was marked as the answer   
    You can use plain php curl, but honestly I think it'll be easier to deal with if you use Guzzle. I find it much easier, especially when dealing with passing tokens and keys and whatnot; as the docs say:
    $client = new GuzzleHttp\Client(); $res = $client->request('GET', 'https://api.github.com/user', [ 'auth' => ['user', 'pass'] ]); echo $res->getStatusCode(); // "200" echo $res->getHeader('content-type')[0]; // 'application/json; charset=utf8' echo $res->getBody(); // {"type":"User"...' Give it a shot and come back with code if something goes weird.
  12. maxxd's post in Why am I getting no response from my loginizer.php file? was marked as the answer   
    The data you're sending from AJAX doesn't include a 'submit' index, which loginizer.php requires to do anything.
  13. maxxd's post in Should you pass models directly to view - Laravel was marked as the answer   
    Personally I like to refine and/or finesse the data as necessary in the controller before it reaches the view. This sets up basically very dumb views where any business logic is taken care of before the view is rendered. However, part of the system I'm currently working on does pretty much what you describe and passes raw data directly to the view where it decides what to display and how and it works just fine. As requinix points out, some degree of coupling is pretty much unavoidable so I guess it depends on what's easiest for you reason about.
  14. maxxd's post in Checkbox reset not working - Wordpress customize Add Media was marked as the answer   
    Check boxes aren't be set in $_POST (so it won't be in $attachment, I believe) if they're not checked on the form. So, the isset() won't update the record if the user deselects the check box. What I'd recommend is get the existing post_meta for the record before you try to update. If the value exists, your system will know that the user has deselected the previously selected checkbox and you can delete the post_meta record. If the post_meta data didn't previously exist, then the user never has checked the box and you can skip the update.
  15. maxxd's post in In demo access to my site without authorization was marked as the answer   
    I assume you've got the authorization functionality working? So, instead of hitting the database and checking the user's access level or user role, just return the appropriate value to allow the user in thereby fooling the system into thinking the authorization mechanism returned true.
  16. maxxd's post in email form was marked as the answer   
    OK - is anything being displayed? Add
    <?php error_reporting(E_ALL); ini_set('display_errors', true); ?> to the very top of your script. Do you get an error before you try to submit the form? Or after?
     
    Just looking at it, it could be that you're trying to send an email to the literal string '$name' - single quotes in PHP don't allow variable parsing. Plus, they're not necessary in this instance.
     
    And all joking aside, please do check into some validation before you use the mail() function. You'll be glad for it later.
  17. maxxd's post in Uncaught SyntaxError: Unexpected token < in JSON was marked as the answer   
    Typically this happens when PHP outputs an error. Check your console and see what the output is from the server. Looking at your $queryForCheckInLijst, it may be a SQL error - it looks like you've added a couple column names without commas. I haven't looked through the rest of the code, but that's a place to start.
  18. maxxd's post in Cookie update was marked as the answer   
    The cookie superglobal in PHP is $_COOKIE[], not $COOKIE[]. So that may be part of the problem you're seeing. And as long as you're using the jQuery cookie plugin (which I assume you are from the snippet you posted), you should be able to read the contents of the cookie with:
    console.log($.cookie('calc')); See this SO question for more details. Also note that the jQuery cookie plugin has been deprecated in favor of a non-jQuery dependent version.
  19. maxxd's post in Remove (replace) filter using functions.php was marked as the answer   
    add_filter('woocommerce_bookings_remove_inactive_cart_time', changeDeleteTime()); function changeDeleteTime(){     return time() + ( 30 * 24 * 60 * 60 ); } That should work. What errors are you getting?
     
    By the way, I truly mean should - I've not tested it.
  20. maxxd's post in Newbie needs help was marked as the answer   
    Do me a favor and explain what you mean by 'raw text'.
     
    The widget() function is what renders in the widget area in WordPress. The following part of the code outputs an unordered list of the data.
    // Construct unorganized list for each row echo '<ul class="mycred-this-weeks-leaderboard">'; foreach ( $leaderboard as $position => $data ) { $avatar = get_avatar( $data->user_id, 32 ); echo '<li>' . $avatar . $data->display_name . ' with ' . $mycred->format_creds( $data->total ) . '</li>'; } echo '</ul>'; If it's not spitting out a list as described, it's possible there's escaping on the content. Look for a line in your functions.php file that starts with the following:
    add_filter('the_content', ... After the comma is a function name. Find that function in the functions.php file and see what it does. An escape function in WordPress (like esc_attr(), for instance) will convert special characters into HTML entities, so your output would actually be the HTML markup itself. Now, understand that escaping is important and very much needs to be there, but there are several different escape functions in WordPress, and some are more appropriate than others for some situations.
  21. maxxd's post in Checking the value of a dropdowns in sql php was marked as the answer   
    Then this is a simple JavaScript question, not a PHP question. Create an change event handler to change the background color to the value selected by the user. Note that 'amber' is not recognized by Firefox as a valid color, so you'll probably want to do hex values, but this should get you started:
     
    HTML:
    <tr> <td id='capacity_cell' style='width:300px;height:250px;background-color:grey;'> <label for='capacity'>Capacity</label> <select id='capacity'> <option value=''>Select One</option> <option value='green'>Green</option> <option value='amber'>Amber</option> <option value='red'>Red</option> <option value='black'>Black</option> </select> </td> </tr> jQuery:
    $(function(){ $('#capacity').change(function(e){ var bg = $(this).val(); $('#capacity_cell').css({ backgroundColor: bg }); }); });
  22. maxxd's post in update not working was marked as the answer   
    There's no way for us to tell why it's failing right now as the SQL looks fine. What you need to do is check the results of the query. See if the query failed; if it did check the error using mysqli_error().
    if(!mysqli_query($con, "UPDATE news SET news_title='$news_title', news_content='$news_content', publish='$publish', facebook='$facebook' WHERE news_id='$news_id'")){ print("<p>Don't print the error to screen in a real application; but for testing purposes the error is ".mysqli_error($con)."</p>"); } Also, please note that you're inviting SQL injection by putting suspect data ($_POST values) directly into the SQL. Look into prepared statements - honestly, here's where you're going to find PDO much easier to deal with.
  23. maxxd's post in Getting an error on contact form submission. was marked as the answer   
    You've got output before the call to session_start(). If I'm not mistaken, WordPress replaces shortcode at the point that it encounters it in the loop content. Which means there's the header file, and processing, all the HTML, and any post content before that shortcode that's output to screen before the session_start() call. I'd recommend starting the session either using the init hook, or at the top of your functions sheet.
  24. maxxd's post in Log in error MySQL/MariaDB was marked as the answer   
    Admittedly, it's late so I may be overlooking something, but your connection string looks like it should work assuming the username, password, database name, and host are correct. The only thing I see that looks a little off is the space between the host and dbname assignment. The dsn strings that I've seen and used in the past don't have a space there. So perhaps changing
    $db_connection = new PDO("mysql:host=$host; dbname=$db_name", $db_user, $password); to
    $db_connection = new PDO("mysql:host=$host;dbname=$db_name", $db_user, $password); might help? To make sure the constants.php file is being included, just add a die('Hi there! This is constants.php'); at the top of the script an see if it prints out or not. Might be a path issue, although if you have error reporting turned on that should tell you the file isn't found.
     
    That having been said, the entire logic behind the class you've designed makes no sense. You're assigning the DB connection to a method-scope variable, then calling a static object method to attempt to return the variable you just assigned to the method-scope variable (and which the static object method knows nothing about) to another method-scope variable?
  25. maxxd's post in SQL injections - how to stop was marked as the answer   
    The insert statement is good - you're using a prepared statement. Do the same with the select statement. Also, don't use md5() for your password - MD5 has been pretty much obsolete for quite a while now due to the fact that it's not secure. Use password_hash() and password_verify().
     
    Those are a couple things that jumped out at me on a quick look.
×
×
  • 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.