-1

I'd like to select different data from my database using a function. Unfortunately I don't have access to $pdo in the function. Here is the code for better understanding:

config.php

...
$pdo = new PDO("mysql:host=$host;dbname=$database", $user, $password);

select.php

include 'config.php';

function abc($sql) {
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':name', $name);
    $stmt->execute();
}

$sql = "SELECT a FROM table WHERE b = :name";
abc($sql);

$sql = "SELECT a FROM table WHERE c = :name";
abc($sql);

Error:

Call to a member function prepare() on null

If I put the config.php into the function, it works like a charm.

Dharman
  • 30,962
  • 25
  • 85
  • 135
fnm65404
  • 65
  • 1
  • 5
  • Here is canonical: https://stackoverflow.com/q/16959576/1839439 @billKarwin Could you add it in, please? – Dharman Feb 08 '20 at 17:09
  • I have reopened this question, but I can't re-vote to close now. Please vote this question as a duplicate of https://stackoverflow.com/q/16959576/1839439 – Bill Karwin Feb 08 '20 at 17:16

1 Answers1

0

You may declare $pdo as global, or pass it as a second parameter to abc. What's the problem with that ?

Pierre
  • 643
  • 1
  • 7
  • 14
  • certainly not, a PHP var is not global and can't be accessed withing a function, unless "imported" inside with the `global` keyword. Please refer to PHP doc. – Pierre Feb 08 '20 at 17:04
  • But I should have access to $pdo using $GLOBALS['pdo']? – fnm65404 Feb 08 '20 at 17:07
  • Or even better, how can I pass $pdo to the funcion too? Using abc($sql, $pdo) din't work. – fnm65404 Feb 08 '20 at 17:09
  • if it doesn't work, you `$pdo` var is not initialized correctly I guess. – Pierre Feb 08 '20 at 17:10
  • It worked, I have no idea what I've done before ;). Passing $pdo to the function should be a good solution, right? – fnm65404 Feb 08 '20 at 17:11