-1

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 values ​​coming from the query.

I created two functions to connect to the database and data, but I wanted to know if I can create a global variable because I am using the "New PDO" .

/** Conecta com as impressas **/
function impressoras()
{       
    $PDO2 = new PDO('mysql:host=localhost;dbname=ti','root','xxx');
    $PDO2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    global $stmt;
    $stmt = $PDO2->prepare("SELECT * FROM league");
    $stmt->execute();
    $result = $stmt->fetchAll();
    return $result; 
    echo json_encode($user_arr);    
}
function carrefour()
{
    $PDO3 = new 
    PDO('mysql:host=localhost;dbname=ti','root','xxx');
    $PDO3->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    global $stmt;
    $stmt = $PDO3->prepare("SELECT * FROM lol");
    $stmt->execute();
    $result = $stmt->fetchAll();
    return $result;     
    echo json_encode($user_arr);    
}
deceze
  • 510,633
  • 85
  • 743
  • 889
Joe Doe
  • 57
  • 10
  • 3
    Uhm, yes, you *can* create global variables. Have you tried? Didn't it work? But no, you *shouldn't*. Learn something about dependency injection. – deceze Jul 20 '17 at 12:21
  • _To expand on the above comment_ Basically connect once outside the functions, and then pass the connection variable into the functions as a parameter. ___Avoid GLOBALS whereever possible___ – RiggsFolly Jul 20 '17 at 12:30
  • _Just a small point_ **PDO** was released as a **PECL Extension** in **2005-11-26** So I dont think you can call it **NEW** by any stretch of the imagination – RiggsFolly Jul 20 '17 at 12:32
  • 1
    @Riggs `Parse error: ambiguous keyword 'new', probably interpreted using wrong meaning` – deceze Jul 20 '17 at 13:01
  • @deceze Ahhh NEW as in "Instantiate an Object from a Class" rather than NEW as in "Bright and shiney new" :) – RiggsFolly Jul 20 '17 at 13:04

2 Answers2

1

You could "share" the same database connection object (PDO) very simple in plain old procedural style :-) Here is a simple example:

// config.php
define('DB_DSN', 'mysql:host=127.0.0.1;dbname=test;charset=utf8');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');

// database.php
function db()
{
    static $db = null;
    if ($db === null) {
        $db = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD, array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_PERSISTENT => false,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8 COLLATE utf8_unicode_ci"
        ));
    }
    return $db;
}

Usage

function test1()
{       
    $pdo = db();
    $stmt = $pdo->prepare("SELECT * FROM league");
    $stmt->execute();
    $result = $stmt->fetchAll();
    return $result;     
}

If you prefer a more professional solution then take a look an PHP-DI and use dependency injection.

odan
  • 4,757
  • 5
  • 20
  • 49
0

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:


Here is the code - four PHP pages.

Good luck!

index.php

<?php

require_once 'connection.php';
require_once 'functions.php';

try {
    // Fetch leagues.
    $leagues = fetchLeagues($connection);
    var_dump($leagues); // For testing.

    // Fetch league by id
    // ------------------
    // $leagueId = 1;
    // $league = fetchLeagueById($connection, $leagueId);
    // var_dump($league); // For testing.
    //
    // Insert user
    // -----------
    // $username = 'Sam';
    // $lastInsertId = insertUser($connection, $username);
    // var_dump($lastInsertId); // For testing.
    // 
    // Update user
    // -----------
    // $userId = 6;
    // $username = 'Mikaela';
    // $userUpdated = updateUser($connection, $userId, $username);
    // var_dump($userUpdated); // For testing.
    // 
    // Delete user
    // -----------
    // $userId = 6;
    // $userDeleted = deleteUser($connection, $userId);
    // var_dump($userDeleted); // For testing.    
} 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();
} catch (Exception $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.
    // ...

    // Handle the exception correspondingly.
    // ...
}

connection.php

<?php

require_once 'configs.php';

try {
    // Create a db connection.
    $connection = new PDO(
            sprintf(
                    'mysql:host=%s;port=%s;dbname=%s;charset=%s'
                    , MYSQL_HOST
                    , MYSQL_PORT
                    , MYSQL_DATABASE
                    , MYSQL_CHARSET
            )
            , MYSQL_USERNAME
            , MYSQL_PASSWORD
            , array(
        PDO::ATTR_ERRMODE => 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

<?php

// Db connection parameters.
define('MYSQL_HOST', '...');
define('MYSQL_PORT', '3306');
define('MYSQL_DATABASE', '...');
define('MYSQL_CHARSET', 'utf8');
define('MYSQL_USERNAME', '...');
define('MYSQL_PASSWORD', '...');

functions.php

<?php

/**
 * Fetch leagues.
 * 
 * SELECT * FROM [table-name] WHERE [col1]=:[val1] [oper] [col2]=:[val2]
 * 
 * @param PDO $connection Connection instance.
 * @return array Leagues list.
 */
function fetchLeagues($connection) {
    $sql = 'SELECT * FROM league';

    $statement = $connection->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.

  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/155532/discussion-between-aendeerei-and-your-common-sense). –  Sep 28 '17 at 16:06
  • @YourCommonSense Update: I read your tutorial again right now. You are suggesting to let PDOExceptions be handled by the PHP engine itself (or by a corresponding general error handler) in the case of just displaying the exception in form of a user-friendly message, or of a redirect to a corresponding error page. And, if some special catch customization is required, then use try-catch and rethrow... –  Sep 28 '17 at 16:40
  • @YourCommonSense Well, now I see what you were trying to tell me. Yes, this is a good method and your tutorial explanations are perfect. It seems that I didn't read it with much attention the first time. My bad! Thanks, bye. P.S: The method I didn't use until know. But I will. –  Sep 28 '17 at 16:41