function prepare() on a non-object

Problem inserting data into a database

Page 1 of 1

3 Replies - 3176 Views - Last Post: 07 December 2010 - 12:56 AM Rate Topic: -----

#1 xonorageous  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 06-December 10

function prepare() on a non-object

Posted 06 December 2010 - 03:41 PM

Hello,

I'm currently working on a small project for managing member subscription to a site (instead of using syfony or PHP Pear...).

However once the data is sent from the form I keep on getting the following message :

Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\lessons\members\model\inscription.php on line 16

The code I have written is the following :

<?php

	try
	{
		$db = new PDO('mysql:host=localhost;dbname=test', 'root', '');
	}
	catch (Exception $e)
	{
		die('Error : ' . $e->getMessage());
	}
	
	function inscription($username, $pass, $email)
	{
		$pass_hash = sha1('$pass');
		
		$request = $db->prepare('INSERT INTO members(username, password, email, inscription_date) VALUES(:user, :pass, :email, CURDATE())') or die(print_r($db->errorInfo()));
		$request->execute(array(
							'user' => $username,
							'pass' => $pass_hash,
							'email' => $email));
	}
?>



I think this should be enough code for somebody to find the problem. If not just say and I'll post the rest.

Thank you

Xonorageous

Is This A Good Question/Topic? 0
  • +

Replies To: function prepare() on a non-object

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6066
  • View blog
  • Posts: 23,526
  • Joined: 23-August 08

Re: function prepare() on a non-object

Posted 06 December 2010 - 03:51 PM

$db doesn't appear to be visible to the inscription() function. Either pass it in as an argument to the function (my suggestion) or tell the function you want to use the global $db variable by adding global $db; before you use $db in the function.
Was This Post Helpful? 1
  • +
  • -

#3 Dormilich  Icon User is online

  • 痛覚残留
  • member icon

Reputation: 3541
  • View blog
  • Posts: 10,250
  • Joined: 08-June 10

Re: function prepare() on a non-object

Posted 06 December 2010 - 11:25 PM

when using PDO, there is no need for you to die(). see this tutorial
Was This Post Helpful? 1
  • +
  • -

#4 xonorageous  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 06-December 10

Re: function prepare() on a non-object

Posted 07 December 2010 - 12:56 AM

Thanks for the answers. For the die, I don't normally use it, I was just wondering if it would throw up any new information about the problem. The problem was with the $db. I had used it when calling the function but forgot to put it in the function itself as a parameter :(

Thanks to everyone

Xonorageous
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1