Note that there are some explanatory texts on larger screens.

plurals
  1. POMultiple Databases using PDO
    primarykey
    data
    text
    <p>I'm pretty new to using PDO and I would like to set it up so I can have multiple databases as and when I need them. So I've created a function that allows you to pass a database name to be used as and when.</p> <p>It does work to a certain extent, as in it selects the database you pass in but even if the database is omitted or incorrect it still allows you to select tables and rows from a database which seems to be selected at random based on the MySQL user.</p> <p>This isn't a major issue I suppose but I would like to get it to where it won't select any data unless a database has been passed to through my function.</p> <p>My code is below and I would appreciate your thoughts on how I may better approach this. Thanks.</p> <p><strong>index.php</strong></p> <pre><code>require 'app/cream.php'; try { $db = new Cream_Model(); $db = $db-&gt;selectDb( 'cream' ); $data = $db-&gt;query('SELECT * FROM users'); foreach( $data as $row ) { print_r( $row ); } } catch( PDOException $e ) { echo 'An error has occurrred: ' . $e-&gt;getMessage() . '&lt;br /&gt;'; } </code></pre> <p><strong>Model.php</strong></p> <pre><code>class Model { public $connection; public function connect() { try { $connection = new PDO( DB_DSN . ':' . DB_HOST, DB_USERNAME, DB_PASSWORD, array( PDO::ATTR_PERSISTENT =&gt; true ) ); $connection-&gt;setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $connection-&gt;setAttribute( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC ); } catch( PDOException $e ) { echo 'An error has occurred: ' . $e-&gt;getMessage() . '&lt;br /&gt;'; die(); } return $connection; } } </code></pre> <p><strong>Cream_Model.php</strong></p> <pre><code>class Cream_Model extends Model { public $conn; public function selectDb( $db ) { try { $conn = $this-&gt;connect(); $conn-&gt;exec( "USE $db" ); } catch( PDOException $e ) { echo 'An error has occurred: ' . $e-&gt;getMessage() . '&lt;br /&gt;'; } return $conn; } } </code></pre>
    singulars
    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.
    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