Note that there are some explanatory texts on larger screens.

plurals
  1. POMaking a databaseDo() function for hooking PDO queries
    primarykey
    data
    text
    <p>So I started <a href="http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html#7.1" rel="nofollow">this tutorial</a> as an intro to the PHP PDO. Up until now I've only worked with basic <code>mysql_*</code> type queries. </p> <p>I've noticed that, throughout the tutorial, the <code>connect -&gt; do action -&gt; disconnect</code> pattern is repeated, and only the <code>do action</code> part ever changes. </p> <p>In a real-world setting, would it be a good idea to eliminate repetition by creating a function into which queries can be passed? </p> <p>For example:</p> <h2>a function for handling queries:</h2> <pre><code>&lt;?php function databaseDo($action) { $db_hostname = 'localhost'; $db_username = 'root'; $db_password = 'root'; try { // Establish DB connection $dbh = new PDO("mysql:host=$hostname;dbname=mysql", $db_username, $db_password); echo 'Connected to database'; // Do something $action($dbh); // &lt;- here goes whatever action we wish to perform // Close connection $dbh = null; } catch(PDOException $e) { echo $e-&gt;getMessage(); } ?&gt; </code></pre> <p>Then, suppose I want to perform the action in the first example of the PDO tutorial, I would set it like this:</p> <pre><code>&lt;?php // Define action $insert = function($dbh) { $query = "INSERT INTO animals(animal_type, animal_name) VALUES ('kiwi', 'troy')"; $exec = $dbh-&gt;exec($query); echo $exec; }; // Perform action databaseDo($insert); ?&gt; </code></pre> <h2>Scope of $dbh</h2> <p>I am using $dbh as an argument. Is this the proper way of passing a variable to a function like this without making it global? </p>
    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.
    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