PDO Global Instance New PDO , its possible?

前端 未结 2 1781
执笔经年
执笔经年 2020-12-12 08:36

I am using PHP PDO to connect to my database and run some querys to then use the query return on some forms.

That is, I have a select where it is populated by the va

2条回答
  •  有刺的猬
    2020-12-12 08:47

    Give it a try.

    • You should create only one PDO instance, e.g. connection. It should be passed as argument to each function that uses it.
    • I wrote a function named fetchLeagues() instead of impressoras. Implement function carrefour() in a similar way.
    • I wrote a function fetchleagueById() too, in order to show you how to bind values to the prepared sql statement.
    • I implemented three other example functions (insertUser(), updateUser() and deleteUser()) too, so that you can see the complete CRUD process.

    Some recommendations:

    • Try to move to OOP.
    • Apply the so-called dependency injection instead of implementing globals and statics.
    • Apply exception handling.

    Resources:

    • (The only proper) PDO tutorial
    • Error reporting basics
    • Error handling - PHP Best practices
    • The Clean Code Talks - Don't Look For Things!
    • Dependency Injection and Dependency Inversion in PHP
    • Exception handling

    Here is the code - four PHP pages.

    Good luck!

    index.php

    connection.php

     PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_EMULATE_PREPARES => FALSE,
            PDO::ATTR_PERSISTENT => TRUE,
                )
        );
    } catch (PDOException $exc) {
        // Announce the user about the fact of a raised error, or redirect him to a predefined display-error page.
        echo 'We are sorry for the inconvenience. An error occurred during your request. Please try again or contact the administrator.';
    
        // Log exception to a file.
        // ...
    
        exit();
    }
    

    configs.php

    functions.php

    prepare($sql);
        $statement->execute();
        return $statement->fetchAll(PDO::FETCH_ASSOC);
    }
    
    /**
     * Fetch league by id.
     * 
     * SELECT * FROM [table-name] WHERE [col1]=:[val1] [oper] [col2]=:[val2]
     * 
     * @param PDO $connection Connection instance.
     * @param string $leagueId League ID.
     * @return array League details.
     */
    function fetchLeagueById($connection, $leagueId) {
        $sql = 'SELECT * FROM league WHERE id = :id LIMIT 1';
    
        $statement = $connection->prepare($sql);
        $statement->bindValue(':id', $leagueId, PDO::PARAM_INT);
        $statement->execute();
    
        return $statement->fetch(PDO::FETCH_ASSOC);
    }
    
    /**
     * Insert user.
     * 
     * INSERT INTO [table-name] ([col1],[col2],[col3]) VALUES (:[col1],:[col2],:[col3])
     * 
     * @param PDO $connection Connection instance.
     * @param string $username User name.
     * @return integer Last insert id.
     */
    function insertUser($connection, $username) {
        $sql = 'INSERT INTO users (
                    username
                ) VALUES (
                    :username
                )';
    
        $statement = $connection->prepare($sql);
        $statement->bindValue(':username', $username, PDO::PARAM_STR);
        $statement->execute();
    
        return $connection->lastInsertId();
    }
    
    /**
     * Update user.
     * 
     * UPDATE [table-name] SET [col1]=:[col1],[col2]=:[col2] WHERE [PK-name]=:[PK-name]
     * 
     * @param PDO $connection Connection instance.
     * @param integer $userId User ID.
     * @param string $username User name.
     * @return bool TRUE if update successful, FALSE otherwise.
     */
    function updateUser($connection, $userId, $username) {
        $sql = 'UPDATE users 
                SET username = :username 
                WHERE id = :id';
    
        $statement = $connection->prepare($sql);
        $statement->bindValue(':id', $userId, PDO::PARAM_INT);
        $statement->bindValue(':username', $username, PDO::PARAM_STR);
        $statement->execute();
    
        return $statement->rowCount() > 0;
    }
    
    /**
     * Delete user.
     * 
     * DELETE FROM [table-name] WHERE [PK-name]=:[PK-name]
     * 
     * @param PDO $connection Connection instance.
     * @param integer $userId User ID.
     * @return bool TRUE if delete successful, FALSE otherwise.
     */
    function deleteUser($connection, $userId) {
        $sql = 'DELETE FROM users 
                WHERE id = :id';
    
        $statement = $connection->prepare($sql);
        $statement->bindValue(':id', $userId, PDO::PARAM_INT);
        $statement->execute();
    
        return $statement->rowCount() > 0;
    }
    

    UPDATE:

    As you can see, my code contains code parts which are repeating themself. But I had a long discussion with @YourCommonSense and it had crystallized itself a better method of applying exception handling. @YourCommonSense has written its own tutorial - which I presented as the first resource/link in the above list. You can use his method instead. It has the BIG advantage of eliminating all code repetitions.

提交回复
热议问题