-1

I'm new to PDO so please bear with me. I'm trying to convert my old mysql to PDO but I am getting a "Fatal error: Call to a member function prepare() on a non-object in functions.php on line 5".

So this is functions.php:

<?php
require('config.php');
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
function getSlug($param){
    $sth = $conn->prepare("SELECT * FROM articles WHERE slug = ?");
    $sth->execute(array($param));
    $slug = $sth->fetchAll(PDO::FETCH_ASSOC);
    return $slug;
}
?>

And this is page that generates the error:

<?php
include('functions.php');
$param = $_GET['param'];
$slug = getSlug($_GET['param']);    
?>

It seems like it's the last line $slug = getSlug($_GET['param']); that's causing the issue but I can't work it out, or it might be something elsewhere. Thanks

George
  • 36,413
  • 9
  • 66
  • 103
aphextwig
  • 543
  • 2
  • 9
  • 23
  • 3
    PDO apart, you're trying to use a global variable from a function. If you don't get a notice, you haven't configured PHP to display errors. You need to fix that. – Álvaro González Jan 14 '14 at 12:12

1 Answers1

3

You need to pass $conn into the getSlug function, otherwise it doesn't know what that variable is (and you get your error message):

<?php
require('config.php');
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

function getSlug($conn, $param) {
    $sth = $conn->prepare("SELECT * FROM articles WHERE slug = ?");
    $sth->execute(array($param));
    $slug = $sth->fetchAll(PDO::FETCH_ASSOC);
    return $slug;
}
?>


<?php
include('functions.php');
$param = $_GET['param'];
$slug = getSlug($conn, $param);
?>
Jon
  • 12,684
  • 4
  • 31
  • 44