Locke
Locke

Reputation: 671

Fatal error: Call to a member function prepare() on a non-object on line 16

I have a registration system on my website and I am changing all my mysql statments to PDO statements. When I changed it, I got this error: Fatal error: Call to a member function prepare() on a non-object on line 16

Here is my code...

<?php

include("sql.php");
    require("includes/password.php");

session_start(); //Start session for writing

$errmsg = array(); //Array to store errors

    $noterr = array();

$errflag = false; //Error flag

function UniqueID() {
$UID = rand(); //Create unique ID
$check = $db->prepare('SELECT * FROM `users` WHERE `UID` = :UID'); //line 16

    $UIDarray = array(
        UID => $UID
);

    $check->execute($UIDarray);

sql.php...

<?php

ob_start();
session_start();

//database credentials
$dbhost = 'dbhost';
$dbuser = 'dbuser';
$dbpass = 'dbpass';
$dbname = 'dbname';

$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

Upvotes: 0

Views: 163

Answers (2)

Sean
Sean

Reputation: 12433

Your database connection - $db - is out of scope. see http://www.php.net/manual/en/language.variables.scope.php

You need to either add it as a function parameter

function UniqueID($db) {
                  ^^^

and when you call the function

UniqueID($db)

OR Place the include inside your function

function UniqueID() {
    include("sql.php");

OR declare the global

function UniqueID() {
 global $db

Upvotes: 1

dethtron5000
dethtron5000

Reputation: 10841

Scope in PHP is not global. Your $db->execute call is within the UniqueID function, and the function isn't able to access the $db variable defined in sql.php. If you alter your UniqueId function to accept a database parameter, and then pass that parameter to the function, you'll be able access it.

Upvotes: 1

Related Questions