How to define a connection within a function to link a pdo to a DB
Hi guys, I just started trying to convert my query structure to PDO and I ran into some weird problem. When I call a pdo request connection inside a function and the connection is enabled outside of the function, the connection becomes undefined. Does anyone know what I am doing wrong here? I was just playing around with it, my example is below.
include("includes/connection.php");
function query(){
$user='user';
$id='100';
$sql = 'SELECT * FROM users';
$stmt = $conn->prepare($sql);
$result=$stmt->execute(array($user, $id));
// now iterate over the result as if we obtained
// the $stmt in a call to PDO::query()
while($r = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "$r[username] $r[id] \n";
}
}
query();
+2
a source to share
1 answer
Your scope does not have access to the variable $conn
, one way to get around these problems is by using global variables . Here's an example:
function query(){
global $conn;
// your code here...
}
Search StackOverflow for Singleton , Factory , Registry and Dependency Injection . Templates for other more advanced and elegant alternatives.
+2
a source to share