how to have defined connection within function for pdo communication with DB
Posted
by Scarface
on Stack Overflow
See other posts from Stack Overflow
or by Scarface
Published on 2010-05-16T16:28:46Z
Indexed on
2010/05/16
16:40 UTC
Read the original article
Hit count: 290
hey guys I just started trying to convert my query structure to PDO and I have come across a weird problem. 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();
© Stack Overflow or respective owner