how to have defined connection within function for pdo communication with DB
- by Scarface
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();