user3233623
user3233623

Reputation: 383

Call PDO from a function

This function returns a row from the database and prints it in the browser.

<?php  

$an_int = 12;    

// If this is an integer

if (is_int($an_int)) 

{

$conn = new PDO('mysql:host=localhost;dbname=pushchat', 'pushchat', 'd]682\#%yI1nb3');
    global $conn;

$stmt = $conn->prepare("SELECT IdPhoto, device_token, IdUser FROM photos ORDER BY IdPhoto DESC LIMIT 300 ");

$stmt->execute();

$result = $stmt->fetch(PDO::FETCH_ASSOC);

print_r($result);

}

?>

How can one call the above code from a standard fucntion? Right now the browser doesn't output anything yet.

<?php  

function new_function()

{

$an_int = 12;    

// If this is an integer

if (is_int($an_int)) 

{

$conn = new PDO('mysql:host=localhost;dbname=pushchat', 'pushchat', 'd]682\#%yI1nb3');
    global $conn;

$stmt = $conn->prepare("SELECT IdPhoto, device_token, IdUser FROM photos ORDER BY IdPhoto DESC LIMIT 300 ");

$stmt->execute();

$result = $stmt->fetch(PDO::FETCH_ASSOC);

print_r($result);
}

}
new_function();

?>

The browser does not show output with this current syntax. Is there a way to call my original code from inside the new_function function... any ideas?

Upvotes: 1

Views: 87

Answers (1)

Vishnu Nair
Vishnu Nair

Reputation: 2433

Well, in your first file you have declared a global variable global $conn; I don't exactly know why but anyway that would work without any issue because $conn is in global scope.

But in your second case when you declare your global variable inside a function, the function would search for $conn which is in global scope instead of the local variable $conn which apparently has the connection handle.

remove the global $conn from your function and it should work.

more information on variable scopes - http://php.net/manual/en/language.variables.scope.php

Upvotes: 2

Related Questions