Jump to content

requinix

Administrators
  • Posts

    15,223
  • Joined

  • Last visited

  • Days Won

    427

Community Answers

  1. requinix's post in Query Not Returning As Expected was marked as the answer   
    Searching through serialized data... ugh.
     
     
    AND has higher precedence than OR, just like how multiplication has higher mathematical precedence than addition. That means writing

    a OR b AND c 2 + 4 * 5is equivalent to
    a OR (b AND c) 2 + (4 * 5)Applying that to your query we discover you've effectively written
    matches q1 OR matches q2 OR (matches q3 AND is not shop manager AND is subscriber)Use parentheses to force evaluation the way you want:
    (matches q1 OR matches q2 OR matches q3) AND is not shop manager AND is subscriberBut I fear you may discover other problems.
  2. requinix's post in sticky list box was marked as the answer   
    Oh, I missed something that would have been nice to point out.
     
    Remember how you made joke_text sticky? "If the joke_text is present in $_POST then output it"? Start with the same concept except with the author

    if(isset($_POST['author'])) { echo $_POST['author']; }
    then add a condition that the POSTed author matches the author in $data (remembering that what's in $_POST will be the author ID and not the name)

    if(isset($_POST['author']) && $_POST['author'] == $data['id']) { echo $_POST['author']; }
    then change the output to be not the value from $_POST but "selected".

    if(isset($_POST['author']) && $_POST['author'] == $data['id']) { echo 'selected'; }
  3. requinix's post in Is it possible to change my username? was marked as the answer   
    Turns out only the username is supported, not both as I thought. So that's the second lie I've told.
     
    I changed your username.
  4. requinix's post in Problem creating objects dynamically was marked as the answer   
    $modelName[strlen($modelName) - 1] = "";Don't do that. You cannot use [] to remove characters - only replace. What the code above actually does is replace with a \0. 
    I don't know what character you're trying to remove but I suggest looking at rtrim.
     
    [edit] The character is 's'. Which should be obvious given the code and output above. Eh.
  5. requinix's post in Variable not updating was marked as the answer   
    What's $m->get/set? Caching? Is that working correctly? It doesn't look like the ->get is setting any sort of TTL or expiration time...
  6. requinix's post in MYSQL IN working like AND was marked as the answer   
    I'm going to ignore the SQL injection and go for the question itself. In a case like this I would do a GROUP BY + HAVING COUNT

    SELECT id FROM fruit WHERE fruit_name IN ("apple", "banana", "orange") GROUP BY id HAVING COUNT(1) = 3Make sure the id + fruit_name pair is unique, even if the two aren't individually.
  7. requinix's post in Help hide private information was marked as the answer   
    Turns out to be a user group restriction that applies to new users. I've moved you to the regular member group - check that one page again.
  8. requinix's post in png images do not display was marked as the answer   
    Then what does it display? Comment out the header() - do you see any error messages?
  9. requinix's post in How to reference the id of the body tag was marked as the answer   
    1. The PHP is irrelevant. Only the HTML it outputs matters. 2. Actually it kinda does. Those three selectors are all essentially "if"s: if this matches, or if that matches, or if the other one matches, then...
  10. requinix's post in using set_time_limit() was marked as the answer   
    Anecdotally and without any sort of source to back me up, you shouldn't do an indefinite timeout on a blocking function. I think that's from personal experience. Do a "long" timeout of less than a minute, then worst case your loop just jumps back to the start and it starts blocking again immediately.
  11. requinix's post in Searching is very slow was marked as the answer   
    Oh no, it wasn't you. I was stuck on an issue that needed changes at the VM layer for our instance.
     
    But that's just been dealt with, so I've finished the switchover. We're now (back to) running with Sphinx.
  12. requinix's post in Composer autoloading inconsistencies? was marked as the answer   
    That's just the way the author(s) designed and wrote their code: ImageManager uses namespaces, FirePHP uses a singleton pattern, and mpdf doesn't use namespaces. Sometimes there's history behind the decisions, sometimes there's history to the project itself that predates some PHP features or best practices.
     
    Not really much you can do about it.
  13. requinix's post in How do I handle database entry dependent on PayPal payment? was marked as the answer   
    Don't do anything simply based on the user returning from PayPal. It's just a URL. Anybody can visit a URL.
     
    You have to verify the transaction was successful. Personally I prefer to use IPN: PayPal submits a request to your server directly, including information, you verify the information (sending a request back to them in the process), and if everything is good then you consider the payment as being completed.
  14. requinix's post in ssl niginx error was marked as the answer   
    Make sure the bundle has the certificates in the right order: nginx expects yours at the top and the rest of the chain after.
  15. requinix's post in object-to-array function works but throws php warning was marked as the answer   
    Really tired of people wanting arrays over objects...
     
    Look.

    $xml = new SimpleXMLElement("/path_to_file/file.xml", 0, true); // or simplexml_load_file if you insist foreach ($xml->row as $row) { echo "{$row->name} is {$row->age} years old<br>\n"; } See how easy that was? 
     
    As for the actual problem, try it out on a regular array (which has the same problem that objects do).

    echo "<pre>"; print_r(object2array(array("name" => "Happy", "age" => 20))); echo "</pre>";Now try to understand what it is doing:1. Is $object an array? Yes. foreach over it and call object2array on each member.
    2. Is $object["name"] an array? No. Call get_object_vars on it, see that the return value is no good, and call strval.
    3. Is $object["age"] an array? No. Call get_object_vars on it, see that the return value is no good, and call strval.
     
    It's assuming that every single value nested within the $object is either an object or array. And that's not necessarily - or even likely to be - true. It needs to check a) if $object is an array, or b) if $object is an object, or otherwise c) it's neither.
     
    But don't do that. Just use SimpleXML like it's supposed to be used. Objects aren't scary. They won't bite.
  16. requinix's post in Should duplicate values be removed from mysql IN clause? was marked as the answer   
    If the list has only constant values then it will be sorted and MySQL will do a binary search (->). That's one additional comparison every time you double the size of the list.
     
    While not a big difference, I'd remove them: one pass in PHP to remove vs. however-many additional comparisons in MySQL.
  17. requinix's post in Delete PHP Freaks Account was marked as the answer   
    As they said, we don't like to delete accounts around here. While you may no longer need your account, content you've contributed to the forum could be useful for other people browsing around or searching for a solution to their own problem.
     
    All you need to do is... just not use your account. No one will be offended.
  18. requinix's post in Using namespace with autoloader was marked as the answer   
    PHP needs fully-qualified names to determine what classes are. If you write just "PDO" then PHP will think you want the PDO class in the current namespace; if you're not in a namespace then great, otherwise it won't find the class (unless you happen to have one with that name). 
    Write \PDO.
     
    The class will be like "Path\To\Class"; the common answer is to convert backslashes to DIRECTORY_SEPARATORs and look for a matching filename.
    spl_autoload_register(function($classname) { $path = str_replace("\\", DIRECTORY_SEPARATOR, $classname); require "/path/to/classes/{$path}.php"; });But if that's all you need to do then you might as well use the built-in spl_autoload and put your /path/to/classes in the include path.
    spl_autoload_register(); // equivalent to spl_autoload_register("spl_autoload") Your autoloader ignores the entire namespace and only uses the class name. It will not be able to handle multiple classes with the same name but in different namespaces, like "Foo\Example" and "Bar\Example".
  19. requinix's post in syntax error, unexpected ')', expecting '(' was marked as the answer   
    If you want to make sure $argument is an array then you need

    public function authorize($ability, array $arguments)If you want the default value to be an empty array then you need
    public function authorize($ability, $arguments = array())If you want both - which I suspect is the case - then do both.
  20. requinix's post in Reverse Natural Sort issue was marked as the answer   
    Use usort() with strnatcmp() to implement your own sorting algorithm.

    usort($FIRST_NAT_SORT, function($a, $b) { $a1 = strtok($a, "-"); $a2 = strtok(""); $b1 = strtok($b, "-"); $b2 = strtok(""); return strnatcmp($a1, $b1) ?: -strnatcmp($a2, $b2); });[edit] It's been asked so I'll explain: 
    The function to usort() has to return 0 depending on how the two arguments ($a and $b) compare to each other - negative if $a $b. Fortunately that's exactly how strnatcmp() behaves too.
    return strnatcmp($a1, $b1) will handle sorting for just the parts before the hyphens, but if they're equal then you need to compare the parts after the hyphens. $x ?: $y is shorthand for $x ? $x : $y, so

    return strnatcmp($a1, $b1) ? strnatcmp($a1, $b1) : -strnatcmp($a2, $b2);(except the shorthand will only evaluate the first strnatcmp() once) 
    Since strnatcmp() returns 0 if the two are equal and nonzero if not, the function will return that number if the two are not equal because it won't try to do the second comparison.
     
    If they are equal then the second strnatcmp() does get evaluated. It works the exact same way as the first one, except it has a minus sign to negate the return value. Thus the result is backwards: negative if $a2 > $b2 and positive if $a2 $b2. The effect is a descending sort on the values after the hyphens.
     
    To be absolutely explicit about everything you could write that line as

    $compare1 = strnatcmp($a1, $b1); if ($compare1 < 0) { // $a1 < $b1 return -1; } else if ($compare1 > 0) { // $a1 > $b1 return 1; } // $compare1 == 0 and $a1 == $b1 $compare2 = strnatcmp($a2, $b2); if ($compare2 < 0) { // $a2 < $b2 return 1; // opposite result } else if ($compare2 > 0) { // $a2 > $b2 return -1; // opposite result } else { return 0; }
  21. requinix's post in regex none or many ? was marked as the answer   
    There are too many things that are optional in that regex. Either you need to make some stuff required or you should combine some of them with alternation and make the whole set required.

    (first?)(second?)(third?) -> (?:first|second|third)If neither of those then we might have to rebuild the regex from scratch...
  22. requinix's post in Is it possible to do these things? was marked as the answer   
    I think Groot is trying to say he wants to make the page on the other site do something, such as open a popup window upon arrival.
     
    If that's the case then no, it is not possible. You cannot make someone else's site do something it wasn't designed to do.
  23. requinix's post in empty post was marked as the answer   
    A form field will be sent even if it is not visible to the user. Because you have the inputs named "link" you will always receive something like

    link=hariciLink&link=black&link=or
    link=dahiliLink&link=black&link=Örnek:%20http://www.websayfam.comThe hariciLink value overwrites the dahiliLink value because it is later in the form. 
    Easy solution: don't name everything "link". Very easy. Also a good idea.
     
    Otherwise you have to worry about enabling and disabling inputs so that only the right ones get submitted with the form.

    <script type="text/javascript"> $(document).ready(function(){ $('input[type="radio"]').click(function(){ if($(this).attr("value")=="hariciLink"){ $(".box").not(".hariciLink").hide(); $(".hariciLink").fadeIn(300); } if($(this).attr("value")=="dahiliLink"){ $(".box").not(".dahiliLink").hide(); $(".dahiliLink").fadeIn(300); } }); }); </script>That code is what you use to show and hide the different link inputs. To make it enable/disable you can
    <script type="text/javascript"> $(document).ready(function(){ $('input[type="radio"]').click(function(){ if($(this).attr("value")=="hariciLink"){ $(".box").not(".hariciLink").hide(); $(".box").not(".hariciLink").find(":input").prop("disabled", true); $(".hariciLink :input").prop("disabled", false); $(".hariciLink").fadeIn(300); } if($(this).attr("value")=="dahiliLink"){ $(".box").not(".dahiliLink").hide(); $(".box").not(".dahiliLink").find(":input").prop("disabled", true); $(".dahiliLink :input").prop("disabled", false); $(".dahiliLink").fadeIn(300); } }); }); </script>or simply
    <script type="text/javascript"> $(document).ready(function(){ $('input[type="radio"]').click(function(){ $(".box").not("." + this.value) .hide() .find(":input").prop("disabled", true) ; $("." + this.value + " :input").prop("disabled", false) $("." + this.value).fadeIn(300); }); }); </script>Keep in mind that enabling/disabling the inputs comes with a visual change (stuff turns gray) so you should enable inputs before showing them and disable inputs after hiding them; .hide() is instant but if you changed to .fadeOut() then you'd have to disable after the fade out animation finished.
  24. requinix's post in struggling to nail this was marked as the answer   
    But what about a case like

    /search/xbox[/category/:category[/subcategory/:subcategory]]This becomes a problem of balanced brackets - simply checking for [] on either side isn't enough. 
    Two suggestions for how to handle this:
    a) Don't allow optional variables and force the user to make additional routes. I've done this and it helps if you can give the user a way to configure routing in a recursive way, like

    <route path="/search/xbox"> route information here... <route path="/category/:category"> additional overriding information here... </route> </route>The routing system matches as much as it can, gathers all the information along the way, and decides what to do. You could also support
    <route path="/search"> route information... <route path="/xbox"> route information... <route path="/category/:category"> route information... </route> </route> </route>where the route information gathered for just "/search" isn't enough to serve a page and thus results in some 404-type behavior. 
    b) Use regular expressions to turn the route pattern into another regular expression. I've done this one too. With your simple example you could have something like

    $route = "/search/xbox[/category/:category]"; // escape any regex metacharacters already present $regex = preg_quote($route, '#'); // if using # as the pattern delimiters // note that it will escape any of . \ + * ? [ ^ ] $ ( ) { } = ! < > | : - // or you can make this much simpler by not escaping characters and trusting the user to write mostly-regex-safe patterns // transform escaped brackets $regex = preg_replace('/\\\\\[/', '(?:', $regex); $regex = preg_replace('/\\\\\]/', ')?', $regex); // transform variables $regex = preg_replace('/\\\\\w+)/', '(?P<$1>[^/]+)', $regex); // replace [^/]+ with whatever you think matches a variable var_dump($regex); // "/search/xbox(?:/category/(?P<category>[^/]+))?"then
    if (preg_match('#^' . $regex . '$#', $url, $matches)) {gives you stuff like
    Array ( [0] => /search/xbox ) Array ( [0] => /search/xbox/category/consoles [category] => consoles [1] => consoles )The route gets [0] for the full match, and both named (useful) and numeric (useless) captures matching the assorted variables (if present). 
     
     
    Why did I just say all that? Because at 4:30am I'm not seeing a "nice" way of solving your particular problem of dealing with the []s.
  25. requinix's post in INSERT INTO HELP was marked as the answer   
    If you use mysql_error() to get the error message then it will hopefully clue you into those trailing commas.
     
    Also, the mysql extension is really old and it's bad and you need to move to PDO or mysqli instead. Learn about them now and start using them before you write too much code and make it difficult to fix later.
    You also need to learn about prepared statements because any naive hacker could break that code and make Bad Things happen to your site. PDO and mysqli both support prepared statements.
×
×
  • 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.