The logic behind "Call to a member function prepare()" [duplicate] - php

This question already has answers here:
pdo - Call to a member function prepare() on a non-object [duplicate]
(8 answers)
Closed 6 years ago.
I'm writing a function to check for records in my database before executing anything, and i'm getting the error Call to a member function prepare() which i don't quite understand. I've been struggeling for quite some time now, and i'd really appriciate some help
The problem should be with the prepare() in line 19
<?php
$dsn = "xxx"; // Database Source Name
$username="xxx"; // User with acress to database. Root is MySQL admin.
$password="xxx"; //The user password.
try {
$conn = new PDO($dsn, $username, $password);
$conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: ".$e->getMessage();
}
//------------------------ Does the category already exist? -------------------------
function checkuser($fbid,$fbfname,$fblname,$femail) {
$sql="SELECT COUNT(*) AS subjectcount FROM Users WHERE Fuid=:Fuid";
try {
$stmt = $conn->prepare($sql);
$stmt->bindValue(":Fuid",$_SESSION['FBID'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$subjectcount=$row["subjectcount"];
} catch (PDOException $e) {
echo "Server Error - try again!".$e->getMessage();
}
//------------------------ If it dosn't, insert it -------------------------
if ($subjectcount==0) {
And i'm having a hard time debugging since i dont quite understand the cause of this error.
I updated my code to
<?php
$dsn = "xxx"; // Database Source Name
$username="xxx"; // User with acress to database. Root is MySQL admin.
$password="xxx"; //The user password.
try {
$conn = new PDO($dsn, $username, $password);
$conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: ".$e->getMessage();
}
//------------------------ Does the category already exist? -------------------------
function checkuser($fbid,$fbfname,$fblname,$femail) {
global $conn;
$sql="SELECT COUNT(*) AS subjectcount FROM Users WHERE Fuid=:Fuid";
try {
$stmt = $conn->prepare($sql);
$stmt->bindValue(":Fuid",$_SESSION['FBID'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$subjectcount=$row["subjectcount"];
} catch (PDOException $e) {
echo "Server Error - try again!".$e->getMessage();
exit;
}
//------------------------ If it dosn't, insert it -------------------------
if ($subjectcount==0) {

I guess the full error message is:
Fatal error: Call to a member function prepare() on a non-object
Right?
You are calling the member function (= function which is a member of a class instance) prepare of the variable $conn which is not declared in the scope of your checkuser function, it's declared outside (in global scope)!
To "import" it into your function so you can access it, put this line at the top of your function:
global $conn;
Also, it looks like you don't have full error reporting enabled, otherwise you would have seen this error before the fatal one, giving you another clue:
Notice: Undefined variable: conn
(By the way, you should exit; after outputing the DB error message in your catch block - otherwise you will print the error but continue to the rest, with a nonexisting DB connection!)

Related

PHP: Why isn't my count(); printing out my array? [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
I'm currently doing a populating/editing my DB using PHP on a webpage I'm going to build. I'm relatively new to PHP so please excuse my "greenhorn" knowledge. My DB connection works, however, I don't understand why my function "displaySQL" and then counting the quantity as an array is not generating anything on my webpage. There's no number displayed on the screen, I was going to have that value put inside an HTML table afterwards. My DB settings are also established for the parameter part (host, username, password). Thanks for any help.
class User{
var $conn;
function __construct($hostname,$username,$password){
try{
$conn = new PDO("mysql:host=$hostname;dbname=pjj5",
$username, $password);
echo "Connected successfully <br>";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
//display all users information
function displaySQL(){
$sql = "SELECT * FROM accounts";
$q = $conn->prepare($sql);
$q->execute();
$results = $q->fetchAll();
return $results;
}
$db = new User($hostname,$username,$password);
$res = $db->displaySQL();
echo count($res);
To access a variable of an object within the object you need to use the syntax $this->.
This line:
$conn = new PDO("mysql:host=$hostname;dbname=pjj5",
$username, $password);
and this line
$q = $conn->prepare($sql);
should have $this->conn instead of $conn. In the first function you create the connection to a new $conn variable that is local in scope to the function only, which gets discarded after the object is constructed. For the function displaySQL() $conn is undefined.

Fatal error: Call to a member function prepare() on boolean in

I red several questioins, but no one helped.
Fatal error: Call to a member function bind_param() on boolean in -> nope.
Fatal error: Call to a member function prepare() on null -> nope.
Fatal error: Call to a member function count() on boolean -> nope.
Fatal error Call to a member function prepare() on null -> nope.
fatal error call to a member function prepare() on resource -> nope.
Error: Call to a member function prepare() on a non-object -> nope. I am done..
I am using PHP5 and mySql with PDO:
Connection and Select works fine, but the Insert didnt want to work.
That's my function:
function AddNewUser($nickname, $email)
{
ini_set('display_errors', 1); //DELETE ME
ini_set('expose_php', 1); //DELETE ME
$pdo = EstablishDBCon();
echo "Subscribe user..<br/>";
$sql = "INSERT INTO db.table (nickname, email, insertdate, updatedate) VALUES (:nickname, :email, :insertdate, :updatedate)";
try {
$stmt = $pdo->prepare($sql); //Error at this line
//id?
$stmt->bindParam(':nickname', $nickname, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':insertdate', date("Y-m-d H:i:s"), PDO::PARAM_STR);
$stmt->bindParam(':updatedate', null, PDO::PARAM_NULL);
$stmt->exeute();
CloseDBCon($pdo);
echo "Subscribed!<br/>";
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
The DB pattern is:
id (int not null auto_inc) | nickname (varchar not null) | email (varchar not null) | insertdate (datetime) | updatedate (datetime)
I am new to php and I do not understand that type of error.
I marked the line inside the code, where the error is thrown:
$stmt = $pdo->prepare($sql); //Error at this line
Can someone help me?
Thanks in advance!
//EDIT:
Connection aka db_connection.php:
<?php
echo 'Establishing MySQL Connection<br/>';
$pdo = null;
$dsn = 'mysql: host=xx; dbname=xx';
$dbUser = 'xx';
$pw = 'xx';
try {
$pdo = new PDO($dsn, $dbUser, $pw);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connection established.<br/>';
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
return $pdo;
?>
Here is the EstablishDBCon function:
function EstablishDBCon()
{
$pdo = include_once 'db_connection.php';
return $pdo;
}
The best way to reuse functions is to put it inside of the include file, then include it at the top of each file you'll need it. So inside of your db_connection.php, create your function:
function EstablishDBCon()
{
$pdo = false;
try{
// Put your PDO creation here
} catch (Exception $e) {
// Logging here is a good idea
}
return $pdo;
}
Now you can use that function wherever you need it. Make sure you always make sure $pdo !== false before you use it, to make sure your connection hasn't failed.
The problem is in the function EstablishDBCon(), which expects the include_once statement to return a value as if the contents of the included file are a function.
function EstablishDBCon()
{
$pdo = include_once 'db_connection.php';
return $pdo;
}
But that's not how include_once works here:
if the code from a file has already been included, it will not be included again, and include_once returns TRUE.
That's why you end up with TRUE (a boolean) in your $pdo variable.
In any event, this kind of construction makes your code really hard to follow.
I recommend only using include and friends to combine self-contained PHP functions together, or to embed parts of HTML pages in one another.
Call to a member function on boolean in this case means that $pdo is not an object, it's a boolean. So it's likely that EstablishDBCon() is returning either a true on success or false otherwise, as opposed to a database resource. Double-check the docs on that function. Here's a link to some relevant documentation on PDO that you'll need.

Problems connecting to MySQL using PDO

I've been trying to convert my application from using the depreciated mysql syntax to PDO for connecting to the database and performing queries, and it's been a pain so far.
Right now I have a class, db_functions.php, in which I'm trying to create a PDO connection to the database, as well as perform all the CRUD operations inside of.
Here is a sampling of the code:
db_functions.php
<?php
class DB_Functions {
private $db;
// constructor
function __construct() {
require_once 'config.php';
// connecting to mysql
try {
$this->$db = new PDO('mysql:host=localhost;dbname=gcm', DB_USER, DB_PASSWORD);
}
catch (PDOException $e) {
$output = 'Unable to connect to database server.' .
$e->getMessage();
exit();
}
}
// destructor
function __destruct() {
}
public function getAllUsers() {
try {
$sql = "select * FROM gcm_users";
//$result = mysql_query("select * FROM gcm_users");
$result = $this->$db->query($sql);
return $result;
}
catch (PDOException $e) {
$error = 'Error getting all users: ' . $e->getMessage();
}
}
With that code, i'm getting the following error:
Notice: Undefined variable: db in C:\xampp\htdocs\gcm\db_functions.php on line 12
Fatal error: Cannot access empty property in C:\xampp\htdocs\gcm\db_functions.php on line 12
Line 12 is:
$this->$db = new PDO('mysql:host=localhost;dbname=gcm', DB_USER, DB_PASSWORD);
How could I fix this so that I have a proper instance of a PDO connection to my database that I can use to create queries in other methods in db_functions, such as getAllUsers()
I used the answer found at How do I create a connection class with dependency injection and interfaces? to no avail.
TYPO
//$this->$db =
$this->db =
same here
//$this->$db->query($sql);
$this->db->query($sql);
and i also would use 127.0.0.1 instead of localhost to improve the performance otherwise making a connection will take very long... a couple of seconds just for connection...

PDO Error In SignUp Class

I'm working on my own SignUp class but it seems I have a problem with the PDO calls
The browser returns this to me:
Fatal error: Call to a member function query() on a non-object
I have my database configuration in a file included then on the main page. It's as follows:
<?
$dsn = 'mysql:dbname=magazin-online;host=localhost;';
$username = 'root';
$password = '';
try{
$pdo = new PDO($dsn, $username, $password);
}catch(PDOException $e){
echo 'Connection failed!: '.$e->getMessage();
}
An the line in the SignUp class causing the error is this:
$pdo->query("insert into ... () ... values ());
Now, I don't make any db connection in my SignUp class because I already included the file resposible for it.
How can I get rid of that error?
try using exec instead of query:
$pdo->exec("insert into ... () ... values ());
You are catching the exception generated by the new PDO, and then continue execution.
By doing it this way, you have to check that the class exists, so change:
if( $pdo)
$pdo->query("insert into ... () ... values ());
But .. a better way is not to continue execution after a critical error like this.
So better change the connection like this:
$dsn = 'mysql:dbname=magazin-online;host=localhost;';
$username = 'root';
$password = '';
try{
$pdo = new PDO($dsn, $username, $password);
}catch(PDOException $e){
echo 'Connection failed!: '.$e->getMessage();
die;
}
If I understand correctly, $pdo is a global variable. If you are calling $pdo->query inside a function, you either have to pass the $pdo connection as a parameter or declare it as global
global $pdo;
in the beginning of the member function.

Check username exists using PHP and PDO?

I have a db.php file that has the following in it:
// db.php file
// creates connection to database
// DATABASE CONNECTION FUNCTION
function sql_con(){
try{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
// log error to file and display friendly error to user
ExceptionErrorHandler($e);
exit;
}
}
I have a signup page and i want to check if username already exists, so i call my sql_con(); function beforehand to connect to database then do the below query
// connect to database
sql_con();
$stmt = $dbh->prepare("SELECT `user_login` FROM `users` WHERE `user_login` = ? LIMIT 1");
$stmt->execute(array($username));
if ( $stmt->rowCount() > 0 ) {
$error[] = 'Username already taken';
}
I'm very new to PDO and with the above i get the following errors:
Notice: Undefined variable: dbh in C:\wamp\www\signup.php on line 64
Fatal error: Call to a member function prepare() on a non-object in
C:\wamp\www\signup.php on line 64
Probably something very silly and I seem to confuse myself with PDO as I'm at the beginner stages. Could anyone tell me what I am doing wrong? Also I am not sure if this is the correct way as I'm new to PDO so if there's a more efficient way to do the username query check then please let me know.
This is because the $dbh object is limited to inside the try catch block and your sql_con() function due to scope.
The correct solution would be to remove the try catch block, and return the $dbh variable at the end of the sql_con() function.
Then:
try {
$dbh = sql_con();
$stmt = $dbh->prepare("SELECT `user_login` FROM `users` WHERE `user_login` = ? LIMIT 1");
$stmt->execute(array($username));
if ( $stmt->rowCount() > 0 ) {
$error[] = 'Username already taken';
}
}
catch (PDOException $e) {
//Do stuff with $e
}
The $dbh variable is destroyed once the function is done executing.
You could try returning the handle:
function sql_con() {
// your connection code
return $dbh;
}
Then in your signup page:
$dbh = sql_con();
Depending on your needs, a better alternative would be to employ a DI container.
You are defining pdo in function an ist not visible out it.
function sql_con(){
try{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh; //this
} catch (PDOException $e) {
// log error to file and display friendly error to user
ExceptionErrorHandler($e);
exit;
}
}
$dbh = sql_con();
It will be better if you create a class for pdo abstraction.
$dbh = DB::getInstance();

Categories