-2

I'm making a script using PHP and PDO syntax. And before I start I wanted to make some shortcuts for me. $db->query() = qr() and $string->fetch(PDO::FETCH_OBJ) = fet($string)

but a problem pops up on my page, that query() doesn't work inside a function

( Fatal error: Call to a member function query() on a non-object )

Here's my code

// $db->query() = qr()
function qr($str)
{
    return $db->query($str);
}
// $string->fetch(PDO::FETCH_OBJ) = fet($string)
function fet($dbq)
{
    return $dbq->fetch(PDO::FETCH_OBJ);
}

$qr = qr("select * from example");
$fet = fet($qr);

echo "".$fet->example."";
Trogvar
  • 866
  • 5
  • 17
Ali Almoullim
  • 934
  • 8
  • 29

1 Answers1

3

Because $db is not available in function. You have to pass it via function parameter.

function qr($db, $str)
{
    return $db->query($str);
}

Don't use Global variable

Community
  • 1
  • 1
Yogesh Suthar
  • 29,554
  • 17
  • 66
  • 96