• Anonymous
    # August 22, 2014 at 11:46 am

    How can i prepare this PHP code to make it more secure and reliable?


    // Include database connection file
    // get database data
    try {
        $sql = "SELECT ID, TITLE, COVER_URL FROM movies ORDER BY id DESC";
        $q = $connect -&gt; query($sql);
        $q -&gt; setFetchMode(PDO::FETCH_ASSOC);
    } catch( PDOException $e ) {
        echo "Could not retrieve data from the database";


    # August 22, 2014 at 12:47 pm

    By defining $connect in another file and then importing it into scope using require_once, you might eventually find yourself in a situation where it doesn’t actually become available. It’s better to pass the connection explicitly where you need it… but if you’re sticking to a procedural programming style, what you’re doing will usually work just fine. You might want to do something like:

    require_once 'php/db-connect.php';
    if( ! $connect instanceof PDO ){
        /*  something didn't work  */

    I’d also prefer to show the user an actual error page, rather than just dropping dead with a brief notice.

    Other than that, are you trying to address any specific problem(s)?

    # August 22, 2014 at 1:04 pm

    No. There are no problems at all with it now but i’m being very cautious when learning PHP. So i guess ill leave it like that if theres no issue

    # August 22, 2014 at 3:09 pm

    It’ll work fine for most (probably the majority of typical) projects. It’s not a bad pattern, but it will become more fragile as your app becomes more complex. It also won’t work well if you adopt a more functional or object-oriented programming style — so, basically, it depends on what you want to do.

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.