Search code examples
phpmysqlpdoprepare

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


Question is why is this a non-object. The DB is connected successfully and the table is there as well as the columns.

This is my code.

<?php
$config['db'] = array(
    'host'      => 'localhost',
    'username'  => 'root',
    'password'  => '',
    'dbname'    => 'inb271assignment'
);

$pdo = new PDO('mysql:host=' . $config['db']['host'] . '; dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);

//New Data
$username = 'albert';
$password = 'ben';

$query = "INSERT INTO members (Username, Password) VALUES (:username, :password)";
$q = $conn->prepare($query);
$q->execute(array(':username' => $username,
                  ':password' => $password));

?>

And this line gives the error.

$q = $conn->prepare($query);

Thanks.


Solution

  • The error is that you are declaring the PDO connection object to be $pdo and you are using prepare on $conn.

    $q = $pdo->prepare($query);