1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

A PDO class to make it easy on newbies and lazy coders

Discussion in 'PHP' started by eritrea1, Oct 8, 2013.

  1. deathshadow

    deathshadow Acclaimed Member

    Messages:
    8,976
    Likes Received:
    1,635
    Best Answers:
    233
    Trophy Points:
    515
    #21
    In other words you're not building a website, you're making a in-house crapplet which is a whole different story. There's a LOT you can get away with on crapplets you can't on something ACTUALLY deployed as a content based website. As I said, when you can dictate the browser, and are 100% sure of who will be even allowed to use it, THEN you can go ahead and piss away bandwidth and accessibility.

    You're not web deploying so the rules are different. For the web I'd probably have a chart of checkboxes for time, select the user, and then do a submit without scripting... That way it works without scripting -- and provides a mechanism for all your drag and drop scripting to ENHANCE in far less code. (since you could plug in the data, then extract it for a AJAX post).
    SEMrush
    You wouldn't be worrying about bounce on firstload, different browsers, different metrics, or the general rule of building sites for the Internet : the only thing we know about who will come is we cannot know who will come.

    You pull those stunts on a website, where people can choose to or not to use it, hello bounce. You're not making a website, you're making a crapplet -- whole different ballgame. Building a website you DO have to worry about people turning off Javascript, using non-visual browsers, blocking images to save bandwidth on metered connections or memory on mobile, etc, etc... things you quite obviously don't care about on what you did. Graceful degradation provided by progressively enhancing the page -- which is why for a real website you should make it work without scripting or specified style/presentation FIRST, then enhance it with CSS and then SCRIPTS... You don't do that, it probably doesn't belong on the Internet for general access by the public... and that's why I say 90%+ of what people do with jQuery doesn't belong on websites, and not 100%. There ARE exceptions.

    Though I've never seen anything that jQuery didn't piss all over it's usability, functionality and deployability unless -- as you are doing -- you can completely dictate the hardware, browser, and access.
     
    Last edited: Oct 10, 2013
    deathshadow, Oct 10, 2013 IP
    ryan_uk likes this.
    SEMrush
  2. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    51
    Best Answers:
    33
    Trophy Points:
    150
    #22
    I think accessibility is something of the past, while it sounds mean but it is the truth. The majority of sites have the lowest accessibility ratings, not 1 successful website I know of started with accessibility in mind, it is something that comes after making it and its time for the <1% to be able to use the site.

    I also think that frameworks/libraries are things that should be encouraged to use. I haven't had the pleasure to work for a company that will let you design its applications without using an MVC pattern, it just saves time in the end. The point of frameworks is to make it easier to program. You still need to know PHP to code in a framework environment. You are not learning a new language, but rather new functionality in the framework. Yes, you can create your own MVC, your own ORM libraries, your own mailer libraries, but what company in their right mind will pay you to do that and pay you for it.

    One time, in one of the companies I worked at, the architecture decided that we should build our own ORM/CRUD functionality. The project was finished with two developers working on it full time for a month. To date, there are still bugs that pop-up here and there. Unit testing alone was going to take us extra weeks to finish. We also ended up reducing the functionality for lack of time. When you re-use libraries (which is what I consider frameworks to be, a collection of libraries) it makes your live easier and you finish a project much faster than if you would start from scratch.

    I always try to use as many frameworks as I can. Learning the functionality of a framework wouldn't take an intermediate developer more than a week at most. It will look nicer on your resume and you can tackle any project built on any framework with ease. I also find it good practice to look at the framework core libraries and see how its done, designed and implemented,. It really helps you when time comes to shove and you have to design a system on your own.
     
    ThePHPMaster, Oct 10, 2013 IP
  3. ryan_uk

    ryan_uk Illustrious Member

    Messages:
    3,985
    Likes Received:
    1,022
    Best Answers:
    33
    Trophy Points:
    465
    #23
    Not really. Anyone needing to use a screen reader or similar is not banned from the Internet (but maybe from your sites?). Mobile (smartphone and tablets) is insanely important these days, so functioning well on many different types of display is important. Functionality should be the same regardless of device. Sites should adapt to the screen size. Content should be easily understood. Accessibility is now and the future. If anything, in the past is was crapped all over and lots of hideous junk was produced.

    Any half decent site these days is designed to be usable on mobile and desktop.

    What's the point in learning frameworks? It's better to know how to do it in the actual language. It's pointless learning lots of frameworks, they just lead to crappy coding. If you don't know how to code something then learn. If a developer understands programming principles and a language (rather than a framework) they will easily be able to learn another one, rather than messing around learning the basics of a language and an idiotic framework.
     
    ryan_uk, Oct 10, 2013 IP
    Arick unirow and malky66 like this.
  4. deathshadow

    deathshadow Acclaimed Member

    Messages:
    8,976
    Likes Received:
    1,635
    Best Answers:
    233
    Trophy Points:
    515
    #24
    Which is just more of the "pay more later for something that could have been done easily from the start" attitude.

    If accessibility was something of the past, why would HTML 5-tards even talk about the alleged semantics of the new tags? (admittedly they seem more interested in data scraping asshattery and bots than the entire real reason for semantics) -- If it was something of the past, why is responsive layout a "must have" provided by CSS3? If you're making a government or financial site, do you really want to risk a lawsuit for ADA violations (or fines in the UK)?

    Though that's the real laugh of the whole topic... it's SO **** EASY TO DO, why the hell do scripttards, PSD jockeys, SEO voodoo scammers, and the just plain ignorant/lazy try to make something simple (content delivery) so blasted hard wasting hundreds of K of markup, scripting and presentational images on delivering single digit K of actual content? THEN they make the noodle-doodle claim that using all that crap made it simpler and easier to develop?

    I've seen that one from a lot of developers lately, particularly when they're defending crap that has no business on a website in the first place -- that it's somehow harder for them to NOT do something... Herpafreakingderp!
     
    deathshadow, Oct 10, 2013 IP
    malky66 and ryan_uk like this.
  5. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    51
    Best Answers:
    33
    Trophy Points:
    150
    #25
    Sorry for not making it clear at first -only your first statement applies to what I said, here is what I mean by accessibility:

    http://en.wikipedia.org/wiki/Web_accessibility

    And not web responsive design:

    http://en.wikipedia.org/wiki/Responsive_web_design

    Which I personally think are two different things.

    I totally agree, you need to check the laws and regulations. If it is something you need to do then yeah, you should do it and not risk fines or breaking any laws.
     
    ThePHPMaster, Oct 10, 2013 IP
  6. ryan_uk

    ryan_uk Illustrious Member

    Messages:
    3,985
    Likes Received:
    1,022
    Best Answers:
    33
    Trophy Points:
    465
    #26
    Something far from dead and a thing of the past.

    Then you are not thinking much. They have a lot to do with each other. Think about document order. This is very important for accessibility. Now think about responsive design and document order. Bingo yet? This is just the beginning. Also responding to the device that is reading the document. Properly defined viewports help everyone - with or without visual impairments, for example.

    Web accessibility is far from dead. Some people are making their sites more accessible without even realising it. And others are churning out inaccessible junk.
     
    ryan_uk, Oct 10, 2013 IP
    malky66 likes this.
  7. eritrea1

    eritrea1 Active Member

    Messages:
    182
    Likes Received:
    9
    Best Answers:
    2
    Trophy Points:
    70
    #27

    Hey, I modified the script, a little bit, even thought it was the first time, I ever extended a built-in class. There is a chance I could be doing something very horribly. So, can you please check it and give me a little feedback? this is the link https://github.com/simon-eQ/PdoNoodle
     
    eritrea1, Oct 20, 2013 IP
  8. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #28
    A few things:

    • Don't exit() in your constructor. That makes it impossible to catch the error and continue if the programmer wishes to. Re-throw the exception, or don't catch it at all.
    • Your noodle method (I'd never think I'd say that) returns 3 different data types. That's not very handy because I'd have to check for the type before using the returned value. Thus, rendering your plan to avoid try/catch kinda useless. Maybe if you hate trying and catching, you could pass a third argument as reference, and assign the error message to that if something fails.
      
      
      public function noodle($query, $value = null, &$error = '')
      {
          // ... 
          }catch(PDOException $e){
               $error = $e->getMessage();
          }
          // ...
      }
      
      $pdo->noodle(' [ ... ] ', null, $error);
      
      if ($error)
      {
          // query failed
      }
      
      PHP:
    • And last, your if(strpos($query, 'SELECT') !== false) check would probably fail if I used a SELECT subquery. E.g.:
      DELETE FROM `users` WHERE `userid` IN (SELECT `userid` FROM `banned_users`)
      Code (markup):
      Instead, you could check if the query returned any results (rows), and work from there.
    • Okay, one last thing. In $stmt->execute($value);, you could type-cast $value to array, so that when executing noodle(), you don't have to do noodle(..., array('foo'));
      $stmt->execute((array) $value);
      PHP:
     
    nico_swd, Oct 20, 2013 IP
    eritrea1 likes this.
  9. deathshadow

    deathshadow Acclaimed Member

    Messages:
    8,976
    Likes Received:
    1,635
    Best Answers:
    233
    Trophy Points:
    515
    #29
    One big thing - try/catch will NOT actually 'catch' a parent classes constructor throwing errors. That's why if you notice in that article I linked to I use setExceptionHandler thus:
    final class database extends PDO {
    
         public static function exceptionHandler($e) {
             die('Uncaught Exception:'.$e->getMessage());
         }
         
         public function __construct($settings) {
         
             set_exception_handler(array(__CLASS__,'exceptionHandler'));
             
             parent::__construct(
                 $settings['dsn'],
                 $settings['username'],
                 $settings['password']
             );
             
             restore_exception_handler();
         }
         
     }
    Code (markup):
    You actually have to replace the handler to reliably catch a parent::method, particularly a constructor. Pain in the ass, but there you are.

    I'm not wild about the gathering of all results into a single array -- while that's fine for small data sets, making extra copies of values that already exist in memory or in the engine just increases the memory footprint for no real reason. I'm also a little confused as to why you're iterating the result set to build it in one case, but using fetchAll in another -- shouldn't both be fetchAll? In either case unless the data set is REALLY tiny, fetchAll is generally a bad idea.

    It's also generally a bad idea to just start adding array elements using [] on a variable that hasn't even been defined. Adds extra overhead inside the loop -- though again I'm not even sure what that loop is even there to do... If you are passing values to a compare why are you running QUERY as it it's an array? I'm not sure I get the point of that at all.

    I'm increasingly not convinced that shoving everything into one function is a good idea for queries, particularly when it comes to returning data. They are different functions (query, exec, prepare/PDOstatement::execute) for a reason -- trying to combine them down is making it more complex, not simpler... and teaching bad habits.

    One other little niggling thing -- your indenting style doesn't make any sense and/or line up, and you have a LOT of really pointless comments. Avoid the K&R style "asterisks everywhere" garbage, and likewise avoid REALLY silly comments like:
     /**
         * Create PDO instance
         * @[USER=74751]param[/USER] $dsn
         * @[USER=74751]param[/USER] $user
         * @[USER=74751]param[/USER] $pass
         */
        public function __construct($dsn, $user, $pass){
    
    Code (markup):
    Anyone for whom the method declaration doesn't say the same thing as the wasteful comment, probably has no business in the code in the first place. Should there be no bytecode cache, or a first execute occurs and/or pushed out of cache from infrequent execution, things like comments can actually make the code slower; comment when you NEED to, not just because you can.

    VERY good article about that I always link people to over on IBM's Linux Developer site, it's meant for C programmers, but programmers of all sorts can benefit from it. (were the dipshits writing turdpress would take the time to read it)... I'm particularly fond of the "OH, now we're done?" part.

    http://www.ibm.com/developerworks/library/l-clear-code/

    Now to see how long it is before some ignorant twit gets their panties in a wad because I dared to use a word that SOUNDS like a racial slur, but has NOTHING to do with that...
     
    deathshadow, Oct 20, 2013 IP
    eritrea1 likes this.
  10. eritrea1

    eritrea1 Active Member

    Messages:
    182
    Likes Received:
    9
    Best Answers:
    2
    Trophy Points:
    70
    #30
    I had some free time yesterday, to make changes to the class, but I could only apply 2 changes from your suggested 5 (including the name noodle())


    Although, I understand what this means, but the constructor in this case, has to be exited, othewise, it will show errors that reveal all file name. You see, the problem is, in https://github.com/simon-eQ/PdoWrapper/blob/master/PdoWrapper.php#L45 if I do return instead of exit, for some reason the errors won't be shown, if I do echo only, then the first even though the exception will be caught and displayed, but the rest of the codes will be executed, and obviously, if there is an error in the constructor, then the rest of the method will throw of an ugly error, all over the place. So, the only solution (I could come up with) was to see if there is an error, throw it, and exit the constructor, so as the rest of the script will not run.


    Well, first I have changed the names. Class name is now, PdoWrapper, and method name is: doSimple(); (I am lousy when it comes to name picking) second thing, I agree with making a reference to catch possible errors, but doing

    $pdo->noodle(' [ ... ] ', null, $error);
    
    if ($error)
    {
        // query failed
    }
    Code (markup):
    on each query, would be against the idea of what the class intends to provide, which is a one or two lines of code, for every query. Meaning, it would default a user back to writing as much as he/she would, if they used the PDO the normal way. But, I'm undecided about this, because I like your idea, so I may change my mind.

    Ok, I applied a little change to the above to:

    if(strpos($query, 'SELECT')  < 5){
                
                return $stmt->fetchAll(PDO::FETCH_ASSOC);
                        
            }
    Code (markup):
    It means, that if the SELECT word, is found somewhere before the first 5 characters, then treat it as a select statement. Meaning, if I take your example,
    DELETE FROM `users` WHERE `userid` IN (SELECT `userid` FROM `banned_users`)
    Code (markup):
    It would be false, because, SELECT must be the first/second word in the statement. Which kind of makes sense.



    As far as I know, this one can not be done, unless the value that I am passing is just one. For example, assume that I am passing two values, and I will cast the value to array in execute((array) value) but, still, that does not do anything if the values are more than one, or how to even pass them as array in this method


    select = $db->doSimple('SELECT * FROM users WHERE name = ?', $_POST['Simon']);
    Code (markup):




    Thanks again for the feedback.
     
    Last edited: Oct 28, 2013
    eritrea1, Oct 28, 2013 IP
  11. eritrea1

    eritrea1 Active Member

    Messages:
    182
    Likes Received:
    9
    Best Answers:
    2
    Trophy Points:
    70
    #31


    I didn't understand most of what you said, but I only blame my newbieness for that.

    First, the constructor thing did not make sense to me, maybe it's for more advanced users, much like your article on extending the PDO class. After-all, I am so new, that this is the first time, I had to extend a class in PHP, so progress and versatility are due in the future, not now. The way, I am doing does work though, as it catches the exception with no problems.
    Only drawback is, that I am using echo & exit inside the construct, which I am guessing is not a good approach.

    I understood some of the advises and questions though. You asked, why I was iterating and catching the result into a single variable?
    if you are referring to this line https://github.com/simon-eQ/PdoWrapper/blob/master/PdoWrapper.php#L72 then, it is because, I don't want to use echo, because, I've heard echoing anything from class is a bad idea, and if I use return from this level, then the script will half after returning only the first value of an array. So, the only option is to lump them all together inside an array, and just result the array itself.

    Your other point was about why I used fetchAll. Well, I had to, for the reasons that, the default way of PDO returns the result is FETCH_BOTH, which really does nothing except return the results in duplicate-type format, which I have less words to describe it exactly, what it means, but know enough to decide fetchAll(PDO::FETCH_ASSOC) is better, and faster way to return the required object. (don't quote me on anything here. Remember, I'm still newbie :)


    This is actually, something I didn't thing about, and a good point too. From, one stand point, since I am trying to make a small crud only class, it would be way out of the purpose of the class, to integrate other/all features of PDO, in which case, it would make sense to incorporate different methods to suit different functionality.


    I agree 100% with this. I have left some silly comments, which I am about to clear up, all over the place. Sometimes, since I am newbie, and self-thought at the the top of that, I can't find pure technical explanations to functions or method in computer science manner of wording. Anyway, I will improve on that, and the indentation.


    thanks for the feedback.
     
    eritrea1, Oct 28, 2013 IP
  12. deathshadow

    deathshadow Acclaimed Member

    Messages:
    8,976
    Likes Received:
    1,635
    Best Answers:
    233
    Trophy Points:
    515
    #32
    It actually won't... or more specifically it will end up outputting the connection data. TRY/CATCH uses the default exception handler, which may catch the error, but it outputs some things you may not want output. Overriding the default PHP exception handler with your own lets you make it show only the messageInfo() and nothing else.

    In my code I usually prefer to do all my setup before I start playing with data or letting a page output anything. As such doing an echo before that point is fine if you're gonna let it exit/die. Only thing I would change is that exit and die (same command, one's just an alias) can echo out an exit by themselves, so you don't need to echo before it. Just die('your message'); or exit('your message').

    Those were the SAME question actually. Either way creates extra copies in memory making it slower. Unless you are using the result set as a lookup dumping everything into one massive array is grossly inefficient. The fetch method of FETCH_BOTH or FETCH_ASSOC doesn't even play into it. You're making copies of things that already exist in a grossly inefficient manner, which is why you should be returning the PDOStatement and not an array.

    Really I think you have a logic disconnect on how PDO works. This part:

    Doesn't entirely make sense, but really I suspect you're not grasping how fetch is supposed to be used.

    while ($row = $statement->fetch()) {
    // process $row
    }

    Should be done on the output side of the code (and therein NOT IN YOUR CLASS) as much as possible, which is why you return your PDOStatement, NOT the result set. That way you only have in memory at one time an extra copy of a single row, NOT the entire data set! Keeps memory use under control for better performance. FetchAll OR dumping it into a massive array as the final result set is just making life harder.

    Though that's really why I don't think the overhead of your class is worth the time or effort. It doesn't really simplify anything, at least from a performance standpoint.
     
    deathshadow, Oct 28, 2013 IP
    eritrea1 likes this.
  13. monkeye

    monkeye Member

    Messages:
    307
    Likes Received:
    20
    Best Answers:
    1
    Trophy Points:
    33
    #33
    PDO is not more secure than MySQLi, you can make MySQLi as secure as PDO anytime.

    The thing with PDO is that you can use it with several relational database management system, that's the real difference.
     
    monkeye, Oct 28, 2013 IP
  14. eritrea1

    eritrea1 Active Member

    Messages:
    182
    Likes Received:
    9
    Best Answers:
    2
    Trophy Points:
    70
    #34
    I said, mysql.. Not mysqli. And, I know how PDO can be used with different databases, other than mysql. Which is why, I chose to learn about it.
     
    eritrea1, Oct 28, 2013 IP
  15. monkeye

    monkeye Member

    Messages:
    307
    Likes Received:
    20
    Best Answers:
    1
    Trophy Points:
    33
    #35
    My bad then.
    I thought it worthwhile mentioning as in the past I have come across people using mysqli that were considering switching to pdo for security reasons... no point.
     
    monkeye, Oct 28, 2013 IP
    eritrea1 likes this.
  16. eritrea1

    eritrea1 Active Member

    Messages:
    182
    Likes Received:
    9
    Best Answers:
    2
    Trophy Points:
    70
    #36
    Wow, you really know how to put a man down, don't you? (jk) No worries, though... I'm a newbie, so no hard feeling from me :) But, you should realize that a man with 3 decades of experience and another man, who is not even 3 decades old, and yet whose first 'programming language' is php, which he, btw happens to be self-learning for a year are not the same thing! Although, I am still sure, that I have made some silly mistakes somewhere, but I can't help but assume, that you have not read this tutorial before:
    http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

    Most of my implementations are derived of that page.. for example, you can read the part where it show:


    
    
    query() method returns a PDOStatement object. You can also fetch results this way:
    <?php
    foreach($db->query('SELECT * FROM table') as $row) {
    echo $row['field1'].' '.$row['field2']; //etc...
    }
    <?php
    $stmt = $db->query('SELECT * FROM table');
    
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row['field1'].' '.$row['field2']; //etc...
    }
    
    or
    
    
    <?php
    $stmt = $db->query('SELECT * FROM table');
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    //use $results
    
    
    PHP:
    You can see, now I have chosen the first method, and clumped all the values into an array and then return them instead of echoing, which would only return the first value. You should really read the article. It even tells, why to use fetchAll(PDO::FETCH_ASSOC) instead of other ways...

    But, as of now, I am convinced about returning the pdo statement object than the array, thanks to your suggestion.
    read the article
     
    eritrea1, Oct 28, 2013 IP
  17. deathshadow

    deathshadow Acclaimed Member

    Messages:
    8,976
    Likes Received:
    1,635
    Best Answers:
    233
    Trophy Points:
    515
    #37
    Look at what you just copypasta'd, they are talking the property FETCH_ASSOC, not the method fetchAll. FETCH_ASSOC can be done with EITHER fetch or FetchAll.

    FetchAll results in a larger data set in memory at once, which is why it shouldn't be used in 'all cases'. NOWHERE does that tutorial advocate using fetchAll in all cases. Their first two examples in what you copied to here show it being used with::fetch()

    You know where it says "The default is to fetch with PDO::FETCH_BOTH which duplicates the data with both numerical and associative keys. It's recommended you specify one or the other so you don't have arrays that are double the size!" -- fetchAll can have the same effect.

    Basically it depends on the SQL engine you are calling, but there are two ways SQL works -- the driver or the engine pulls a result set into memory OR by reference on the disk if it's too big to put the result into memory at once. When you call the ->fetch method it pulls one row of the result set into PHP's memory space for you to work with either from the driver or the SQL engine. If you use ->fetchAll to dump all results into an array, you're just making an extra copy in memory of ALL OF IT in memory at once. If your result rows are large enough and you have enough of them, dragging them into PHP all at once can really gut performance -- particularly since PHP can flush and recycle memory to use for data instead of caching. Making an entire large array of all data results has the same basic result, you're making a massive extra copy when you don't need to.

    In both of those routines you should be returning the statement handler, and not the resulting data... though if you do that, it kind-of defeats the purpose of what you are trying to do.
     
    deathshadow, Oct 28, 2013 IP
    eritrea1 likes this.
  18. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    51
    Best Answers:
    33
    Trophy Points:
    150
    #38
    I think that security wise, PDO/MySQLi is just as insecure as MySQL is. It all bottles down to the person writing the code to write secure code. While it is true that PDO/MySQLi have functionality, if used, will make the queries safer, but the same can be said about MySQL as well. Here is a good discussion as why you should be using PDO as opposed to MySQL/MySQLi.
     
    ThePHPMaster, Oct 28, 2013 IP
  19. deathshadow

    deathshadow Acclaimed Member

    Messages:
    8,976
    Likes Received:
    1,635
    Best Answers:
    233
    Trophy Points:
    515
    #39
    Nope, and lemme clue you as to why. SCOPE.

    When you connect thus:
    $conn = mysql_connect("localhost", "mysql_user", "mysql_password");

    The mysql connection is global in scope, which is to say until you do a mysql_close you can blindly call:
    $result = mysql_query($sql);

    without the need to pass $conn to it. There is zero way to restrict the scope of a connection to local or private. This opens MASSIVE holes as it means a script elevation at just about any spot has full access. It ends up as stupid as putting the PW/UN/Host in DEFINE from a security standpoint.

    A lot of people will say "Well just prevent the elevations in the first place" -- one ring does not a secure system make. If you isolate your queries, restrict when/where the un/pw/host/dbname can even be accessed, only return statement handlers, make sure the PDO object is restricted to local or private scope and only sent to functions/classes that need access to it, you'll be far more secure than anything that could EVER be done with the older mysql_ functions -- because you can prevent script injections from revealing anything or even being able to have access to it.

    More so if you chain any includes/requires inside functions to break scope... since the default behavior for include and require can make locals and privates behave like they were globals inside includes. REALLY think PHP needs a native library load so we don't have to do stupid **** like this:

    function safeRequire($file) { require_once($file); }
    Code (markup):
    Just to break scope. The "willy nilly" scope behavior of PHP, particularly when it comes to includes is a massive security gap -- combine that with mysql_ function's effectively permanently global scope, and you're pretty well boned should undesired code get run... Just like how badly systems like turdpress can get pwned in the same scenario with the DUMBASS IDIOTIC HALFWIT DIPSHIT ****TARD placement of username, password, host and database name in undeletable global scope using DEFINE. Whoever came up with that needs a good swift kick in the crotch.
     
    deathshadow, Oct 29, 2013 IP
    ryan_uk likes this.
  20. eritrea1

    eritrea1 Active Member

    Messages:
    182
    Likes Received:
    9
    Best Answers:
    2
    Trophy Points:
    70
    #40


    OK, I hope this will be my last question, before I bore you out to death. I finally, was thinking about simplifying the query to something like this:


    public function doSimple($query, $value = null){
    
            if(empty($value)):
                return parent::query($query);
            else:
            $stmt = parent::prepare($query);
            $stmt->execute($value);
            return $stmt;
            endif;
        }
    PHP:
    So, that way the user can fetch the object in any way they like, and

    
    $wrap = $conn->doSimple("SELECT title FROM pages WHERE id = ?", [19]);
    $row = $wrap->fetchAll(PDO::FETCH_ASSOC);
    print_r($row);
    
    PHP:
    Now, all seems good. Except error handling. The problem is, either way I try to handle the error, it does not seem to have any effect on it. Like this one for example:

    try{
    $wrap = $conn->doSimple("SELECT title FROM unexistingPage WHERE id = ?", [19]);
    $row = $wrap->fetchAll(PDO::FETCH_ASSOC);
    print_r($row);
    }catch (PDOException $e){
        echo $e->getMessage();
    }
    PHP:
    The above code is the same as the second code I pasted, the only change are that I added error handling and tampered with the row name, (changed it from 'pages' to 'unexistingPage') to deliberately catch the error. So, while with the regular plain PDO approach, the error is caught immediately, but not in the above example. Even, if I do the try/catch from withing the class.

    I just need your opinion about two things: If I am doing better by returning the whole statement as in example 1, and let the user manipulate the object, and I also need to know how I can catch the errors in the example I have shown.



    thanks so much, hopefully, this closes the thread.
     
    eritrea1, Oct 29, 2013 IP