phppdo

Can I include one pdo connection


Im a just moving to using PDO for my development and I see in most tutorials that the connection is opend for each db query like in Jeffery Ways example below

$id = 5;
try {
    $conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);   

    $stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
    $stmt->execute(array('id' => $id));

    while($row = $stmt->fetch()) {
        print_r($row);
    }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

Can I still do a connection in an external file and include it at the top of my page like with previous procedural coding and then do my queries below in the page?

<?php include 'includes/db.php';?>

Solution

  • The short answer is yes,

    if you are farmilier with OOPHP it might be worth creating a wrapper class to help with running queries but just creating the connection in a file and including it will get the job done

    in the above example you can put

    try {
        $conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);   
    
        }
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    

    into your db.php and the run the queries

     $stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
     $stmt->execute(array('id' => $id));
    

    wherever you need.

    it may also be worth mentioning that you dont have to use prepared statements with PDO which can speed things up in coding however if you wish to do that i would highly recomend a database wrapper class

    non prepared statement

    <?php
    try {
        $conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);   
    
        }
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    
    $query = "
    SELECT 
      col_1, 
      col_2
    FROM
      table_1
    WHERE
      col_3 = " . $conn->quote($_POST['input']); //the quotr is important, it escapes dangerous characters to prevent SQL injection
    
    
    //this will run the query for an insert this is all thats needed
    $statement = $conn->query($query);
    
    //fetch single col
    $col = $statement->fetch(PDO::FETCH_ASSOC);
    
    //fetch all collums
    $cols = $statement->fetchAll(PDO::FETCH_ASSOC);
    

    the advantage of this way is that you can build up the query SQL in a more simple to follow manner, i should not that i havent tested this code but in theory it should be fine as this is how i do database handling

    Edit: Your Common Sense brings up a good point about the echo 'ERROR: ' . $e->getMessage(); being a bad idea and this is a prime example of why you should NEVER blindly copy and paste code