how to have defined connection within function for pdo communication with DB
hey guys I just started trying to convert my query structure to PDO and I have come across a weird p开发者_Python百科roblem. When I call a pdo query connection within a function and the connection is included outside the function, the connection becomes undefined. Anyone know what I am doing wrong here? I was just playing 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();
Your function scope doesn't have access to the $conn
variable, one way to work around this issues is by using globals. Here is an example:
function query(){
global $conn;
// your code here...
}
Search StackOverflow for Singleton, Factory, Registry and Dependency Injection Patterns for other more advanced and elegant alternatives.
精彩评论