Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to properly set up a PDO connection
    primarykey
    data
    text
    <p>From time to time I see questions regarding connecting to database.<br> Most answers is not the way I do it, or I might just not get the answers correctly. Anyway; I've never thought about it because the way I do it works for me.</p> <p>But here's a crazy thought; Maybe I'm doing this all wrong, and if that's the case; I would really like to know how to properly connect to a MySQL database using PHP and PDO and make it easy accessible.</p> <p><strong>Here's how I'm doing it:</strong></p> <p>First off, here's my file structure <em>(stripped down)</em>:</p> <pre><code>public_html/ * index.php * initialize/ -- load.initialize.php -- configure.php -- sessions.php </code></pre> <p><strong>index.php</strong><br> At the very top, I have <code>require('initialize/load.initialize.php');</code>. </p> <p><strong>load.initialize.php</strong> </p> <pre><code># site configurations require('configure.php'); # connect to database require('root/somewhere/connect.php'); // this file is placed outside of public_html for better security. # include classes foreach (glob('assets/classes/*.class.php') as $class_filename){ include($class_filename); } # include functions foreach (glob('assets/functions/*.func.php') as $func_filename){ include($func_filename); } # handle sessions require('sessions.php'); </code></pre> <p><em>I know there's a better, or more correct, way to include classes, but can't remember what it was. Haven't gotten the time to look into it yet, but I think it was something with <code>autoload</code>. something like that...</em></p> <p><strong>configure.php</strong><br> Here I basically just override some <em>php.ini</em>-properties and do some other global configuration for the site</p> <p><strong>connect.php</strong><br> I've put the connection onto a class so other classes can <em>extends</em> this one...</p> <pre><code>class connect_pdo { protected $dbh; public function __construct() { try { $db_host = ' '; // hostname $db_name = ' '; // databasename $db_user = ' '; // username $user_pw = ' '; // password $con = new PDO('mysql:host='.$db_host.'; dbname='.$db_name, $db_user, $user_pw); $con-&gt;setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $con-&gt;exec("SET CHARACTER SET utf8"); // return all sql requests as UTF-8 } catch (PDOException $err) { echo "harmless error message if the connection fails"; $err-&gt;getMessage() . "&lt;br/&gt;"; file_put_contents('PDOErrors.txt',$err, FILE_APPEND); // write some details to an error-log outside public_html die(); // terminate connection } } public function dbh() { return $this-&gt;dbh; } } # put database handler into a var for easier access $con = new connect_pdo(); $con = $con-&gt;dbh(); // </code></pre> <p><em>Here I do believe there's room for massive improvement since I recently started learning OOP, and using PDO instead of mysql.<br> So I've just followed a couple of beginners tutorials and tried out different stuff...</em></p> <p><strong>sessions.php</strong><br> Beside handling regular sessions, I also initialize some classes into a session like this: </p> <pre><code>if (!isset($_SESSION['sqlQuery'])){ session_start(); $_SESSION['sqlQuery'] = new sqlQuery(); } </code></pre> <p>This way this class is available all over the place. This might not be good practice(?)...<br> Anyway, this is what this approach allows me to do from everywhere:</p> <pre><code>echo $_SESSION['sqlQuery']-&gt;getAreaName('county',9); // outputs: Aust-Agder (the county name with that id in the database) </code></pre> <p>Inside my <code>sqlQuery</code>-<em>class</em>, which <code>extends</code> my <code>connect_pdo</code>-<em>class</em>, I have a public function called <code>getAreaName</code> which handles the request to my database.<br> Pretty neat I think.</p> <p><strong>Works like a charm</strong><br> So that's basically how I'm doing it.<br> Also, whenever I need to fetch something from my DB from not within a class, I just do something similar to this:</p> <pre><code>$id = 123; $sql = 'SELECT whatever FROM MyTable WHERE id = :id'; $qry = $con-&gt;prepare($sql); $qry -&gt; bindParam(':id', $id, PDO::PARAM_INT); $qry -&gt; execute(); $get = $qry-&gt;fetch(PDO::FETCH_ASSOC); </code></pre> <p>Since I put the connection into a variable inside <em>connect_pdo.php</em>, I just have referring to it and I'm good to go. It works. I get my expected results...</p> <p>But regardless of that; I would really appreciate if you guys could tell me if I'm way off here. What I should do instead, areas I could or should change for improvement etc... </p> <p>I'm eager to learn...</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload