Jump to content

maxxd

Gurus
  • Posts

    1,660
  • Joined

  • Last visited

  • Days Won

    52

Posts posted by maxxd

  1. You need to drill into the outer array in order to get to the inner ones. So, if you're actually going to ignore any data other than the contents of the first array index, you'd use

    $parsed_json[0]->name;
    

    to get the value of 'name' in that first array value.

     

    I don't know the business logic behind the feed you're parsing, so I'm not sure if just checking the existence of the name value will work, but the implication is that if the name field contains data, that user is online, right? If so, wouldn't it be possible to assume that if there's a record, there's an online user? Seems like it'd be a bit wasteful to populate a feed stream with empty data. At any rate, you could do something like

    $status = !empty($parsed_json[0]->name) ? true : false;
    
  2. That's not really how a race condition happens. A race condition is going to be a concern mostly when considering something using controlled, unique indices - consider user signup where you've got a system that runs a select query with the requested username supplied by a user, then inserts that username if the select query doesn't return a result. Basically, in this case user A and user B request the same username at almost the same time, both select queries will report that the username is available (ie, not already in the database table). Then user A's insert query is run and suddenly that username isn't available to user B despite the select query - quite correctly - reporting that is was available just a second ago. Or, if there's not a unique constraint on the username field in the database, suddenly you have the same username associated with two distinct records.

     

    What you're describing is a simple insert query. There's no select to check the availability of any index, so no race condition can occur. As everyone has said in this thread, if user A and user B insert a new record at the same time, the worst that's going to happen is that both records will be inserted, which is honestly kind of the point of the thing to begin with. There's no unique constraint (either defined or implied by the business logic) to make this an issue.

  3. You may want to look into a routing system where this is done for you. You can spin your own using PHP and .htaccess, but there are several available online that can take care of it for you and have the benefit of being widely tested and publicly developed. The biggest thing for this is it's easier for your users to remember, it's more search engine friendly, you don't have to write and test it, and you know exactly what you are getting and where it's coming from.

     

    In addition to the things @ginerjm pointed out, I'd highly recommend switching from mysli to PDO. Prepared statements are much easier to deal with in PDO, and you should never, ever inject user-submitted data (such as $_POST variables, let alone $_GET) into a database call. Seriously, don't do it.

     

    You're also declaring $con as a global variable. Although there's nothing technically wrong with doing this, it's not a good idea. Things get very confusing very quickly when you declare a variable to be global; where is that variable declared? What was in it when it was declared? What was put into it later, either by accident or intention? Passing the variable to the function leaves a clear trail of accountability that you can trace when things - as they inevitably do - go south.

     

    I also just noticed that you seem to be running the exact same query twice. Why?

  4. Before you start trying to answer your initial query, you need to look at the underlying database structure - what you've told us about it certainly sounds like it's going to make life more difficult for you moving forward. If you restructure your data as Barand and benanamen have suggested, you'll find your SQL joins to be much more self-explanatory and the data you do receive much more usable. It'll then be two simple joins - one from player_shirt to player and one from player_shirt to shirt to get any number of shirts per player. As it stands now, you're locked in to one shirt per player, and you can't have a player on multiple teams, let alone a user that's a player on one team but captain of another. In order to satisfy your initial request to count the number of shirts, that then becomes a simple COUNT(*) AS num_shirts from the player_shirt table - no joins needed at all.

  5. Thanks, Barand - I meant to link that...

     

    @ohno - There are plenty of people on this board that can. Post in the Job Offerings forum and I'm sure you'll get replies. And depending on your server setup, no, you may not have to upgrade; however, running outdated, unsupported versions of PHP is dangerous to your company and to your company's clients, so you'll want to.

  6. It all works right now - it won't work in the very near future. PHP7 has removed the mysql_* functions that are used all over this code. So at some point in the near future (depending on how quickly your host updates their servers), this one section of code will be the absolute least of your worries. As benanamen and mac_gyver said, you're going to need to have this code rewritten using PDO (or do it yourself).

  7. It's been a long day and I'm tired, but I think your prepared statement is malformed. When using a prepared statement, you only have to actually prepare it once. Try:

    if(isset($_POST['defid'])){
    	$sql = $conn->prepare("INSERT INTO modified_adjustments (default_id) VALUES (:did)";
    	foreach($_POST['defid'] as $did){
    		$sql->execute(array('did'=>$did));
    	}
    }
    

    Of course, you'll want to check for errors and may want to wrap the whole thing in a transaction, but (assuming my brain hasn't broken), that should be the basic idea.

  8. Personally, I'd use DateTime objects.

     

    Right now you're comparing strings which technically does work thanks to PHP's loose typing, but it can lead to hard-to-pinpoint bugs and odd behavior. Not sure what responses your API gives, but if you try to compare "INVALID_ACCESS_TOKEN:INVALID_ACCESS_TOKEN PM" to "12:53 PM", it's going to give weird results. Obviously. However, an incorrectly formatted time string in the constructor of a DateTime object will throw an error that you can handle. Plus, I just find the DateTime objects easier to work with when it comes to comparisons and any mathematical operations.

    • Like 1
  9. No offense, but this is a hot mess. As benanamen points out, you're using code that is about a decade out of date for dealing with the database calls. Not only that, you're attempting to use the $all variable before it's defined and you're not associating any of the 'add to cart' buttons to a specific product so how is your processing script supposed to know which product is meant to be added to the user's cart? I'm not going to go in to the output of raw variables into HTML but you're going to want to look into escaping output, and just the mishmash combination of php and HTML is going to make this a bit of a nightmare to maintain or extend as you move forward. Ideally, you'd use a separate php file to gather your data and a templating system (twig is great, btw) for display.

     

    If you continue forward with the code you've posted, first thing's first - use PDO instead of mysql_* functions. This will allow your site to still be functional later this year. You'll want to gather all the product data into an array at the top of your script, then print out the line items later on in the body of the page. You can do this is one of two ways: create a separate form for each item listed that contains a hidden field with the product ID as mac_gyver suggests, or change the name of the submit button to an array where the key is the product ID as such:

    <input type="submit" class="..." name="my-add-button[product][<?= htmlspecialchars($all['id']); ?>]" value="add to cart" />
    

    That way, when the form is submitted, you know what product the customer actually wants. There shouldn't be a need for the product name or price to be stored in the form as your processing script can grab that data from the database.

    • Like 1
  10. You're not actually validating any of the submitted fields. Just because a value is set in $_POST doesn't mean it's not empty or a blank string, nor does it mean that the field doesn't contain additional mail headers (allowing an unscrupulous user to use your contact form the send spam). I suggest you do some research into data validation, sanitizing, and escaping - it'll make life better for everyone involved.

  11. Quite honestly, ignoring the data retrieval issues you're having, there are several issues with the code you've posted. I'm not sure what your instructor is teaching, but he or she certainly shouldn't be advocating the use of mysql_* functions as they not only have deprecated for about a decade, they're completely removed from the current version of PHP. Hopefully he or she is also explaining the idea of data sanitation because you're dropping variables directly into your query, practically inviting a SQL injection attack.

     

    I'd look very closely at the PDO library and prepared statements - if nothing else you may get extra credit, and you'll definitely get more robust, safer code out of it.

    • Like 1
  12. You can check the value of the field on submission with something like the following completely untested code:

    $('#ap').prepend("<option value='-1'>This is the default option</option>");
    
    $('form').submit(function(e){
    	e.preventDefault();
    	if($('#ap').val() == -1){
    		alert('Fill in the field, please.');
    		return false;
    	}
    	...
    	// continue processing
    }
    

    Of course, you'll want to check the value again during the server-side processing before you do anything with the value, like the also completely untested code below:

    if($_POST['ap'] == -1){
    	throw new Exception('Fill in the field, please.');
    }
    ...
    // continue processing
    
  13. You can, but it's a bit of restructuring. I'd suggest using the PHP to output the necessary values - in this case, loop, swfPath, solution, and title(s) - to an inline JavaScript variable or variables. Then you can grab that object from the included JavaScript file and use the variables there.

  14. Any JavaScript in the HTML is in the global scope, and as such can be accessed from pretty much anywhere. Now then, that being said, putting the script inline is typically frowned upon as it breaks the separation of concerns principle of coding. You want your display code (HTML) in one spot, your client functionality (JavaScript) in another, and your server functionality (PHP) in another place. That way you're not wading through HTML to make changes to PHP or JavaScript.

     

    So, with that out of the way, you can do this -

     

    inline:

    <script>
    	function alertMe(){
    		alert('hi there, me!');
    	}
    </script>
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>
    <script src='yourJavaScriptFile.js'></script>
    

    yourJavaScriptFile.js:

    $.ajax({
    	method: 'post',
    	url: 'yourPhpScript.php',
    	data: {
    		'key' : 'value'
    	},
    }).done(function(data,status,jqxhr){
    	if(stat === 'success' || jqxhr.status === 200){
    		alertMe();
    	}
    });
    

    yourPhpScript.php:

    <?php
    echo('yup');
    ?>
    

    Now, obviously you'll have an event of some sort trigger the Ajax call, and as soon as the Ajax call prints 'yup', the status will be equal to 'success' and jqxhr.status will be equal to 200. So, you should be greeted with an alert window saying 'hi there, me!'.

  15. You would do the string replacement in your form processing method or function. Basically, you'll be doing what you're currently using SQL to do, but in PHP and before the record is inserted or updated in the database.

     

    Something along the lines of:

    $slug = $_POST['userSlug'];
    
    $slug = str_replace(array(' ','&','---'),'-',$slug);
    $slug = str_replace(array('"',"'"),'',$slug);
    
  16. As mac_gyver points out, it's difficult to give decent advice with no idea of the code context. You could do

    $undeclaredVariable = ($a == $b) && ($c == $d);
    

    However, this assumes that there's no additional logic for when $a != $b but $c == $d, or $a == $b but $c != $d, and that there are no additional assignments or operations around the logic for the setting of $undeclaredVariable. Depending on what you're attempting to use $undeclaredVariable for, you'll probably want to set it to false before you start your nest of conditionals.

  17. Not, to be rude but, yes, I think you are missing something.

     

    Not rude at all - it was a genuine question and thanks for taking the time to respond!

     

    The reason to do this is it ensure that the super admin does not lose permission because the role based permissions are accidentally deleted, corrupted, whatever. Imagine the scenario where only the super admin has permissions to edit roles and somehow that permission got deleted for the super admin. There would be no way to resolve the issue through the application. It would require someone with knowledge of the application and access to the DB to create a query to manually add/edit the necessary records. This could be catastrophic if it were to occur when the application is mission critical. Sure, you can build the application to prevent such things, but those pesky business rules to mandate very narrow logic such as that are the ones that get tested the least.

     

    Very true. I guess I rely too much on the idea that someone will be there with the system and database knowledge to fix a mission critical error. Which I really shouldn't do.

     

    And - bugs happen.

     

    Well now that's just crazy talk... :tease-03:

     

    Thanks for all that - interesting ideas and excellent explanation!

×
×
  • 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.