I don't why I'm getting a call to a member function fetch() on a non-object in pdo error. It's really frustrating me!
$db= new PDO($dns,DB_USER,DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$workspace_id=isset($_GET['workspace']) ? (int)$_GET['workspace'] : "";
try{
$sql="SELECT * FROM messages WHERE workspace_id = :id";
$stmt=$db->prepare($sql);
$stmt->bindValue(':id', $workspace_id, PDO::PARAM_INT);
$result=$stmt->execute();
$message=$result->fetch();
}catch(Exception $e){echo $e->getMessage();}
execute()
Returns TRUE on success or FALSE on failure.
In your case you are try to fetch data form bool value
$result=$stmt->execute();
$message=$result->fetch();
Just need to change
$stmt->execute();
$message=$stmt->fetch();
Because $stmt->execute() should return boolean value.
If you want to use the fetch you should call method from $stmt
Documentation: PDOStatement
Related
I'm getting the error:
Call to a member function fetch() on a non-object
The line this refers to is:
$getProjectIdResult = $stmt->fetch();
Now, I think from this error that there must be something wrong with my database query, since the documentation says PDO query returns false on failure. I'm having trouble identifying what is causing the issue.
I've tried wrapping the fetch in a try/catch, with
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
However the catch isn't triggered and I just get the original fatal error so I haven't been able to get a more specific error.
classes.php
class Query extends Connection {
public function getProjectID($surveyID) {
$query_getProjectID = "SELECT projectID FROM test WHERE surveyID = :surveyID";
$query_getProjectID_params = array(
':surveyID' => $surveyID
);
try {
$stmt = $this->db->prepare($query_getProjectID);
$stmt = $stmt->execute($query_getProjectID_params);
}
catch (PDOException $ex) {
die("Failed to get project ID: " . $ex->getMessage());
}
$getProjectIdResult = $stmt->fetch();
$getProjectID = $getProjectIdResult['projectID'];
return $getProjectID;
}
}
test.php
include_once("includes/classes.php");
include_once("includes/functions.php");
// Bind $_GET data
// localhost/panel/test.php?surveyID=3&status=1&respondentID=666
// Expected result: 111
$surveyID = sanitise($_GET['surveyID']);
$status = sanitise($_GET['status']);
$respondentID = sanitise($_GET['respondentID']);
$con = new Connection();
$query = new Query();
$query->getProjectID($surveyID);
$con->closeConnection();
I've ruled out the sanitise function causing an issue by testing with and without it.
I apologise as I know this is probably just another amateur making another amateur mistake judging by how many posts there are by the same title.
When you call
$stmt = $stmt->execute($query_getProjectID_params);
You assign the return-value of execute() to $stmt, overwriting the variable, making it a boolean instead of an object. When you continue, $stmt no longer holds the PDOStatement object, but is now a boolean.
The solution is simply to remove the overwrite of your object, like this (remove $stmt = in front).
$stmt->execute($query_getProjectID_params);
http://php.net/pdostatement.execute
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.
I get this error:
Fatal error: Call to a member function prepare() on a non-object in /home/folder/public_html/includes/name.php on line 1768
This is the function:
function _FC_GET($typ, $data, $username){
global $dbh;
$stmt = $dbh->prepare("SELECT * FROM stats_clicks WHERE typ=:typ AND user=:username AND data=:data LIMIT 1;");
$stmt->bindParam(':typ', $typ);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':data', $data);
try {
$stmt->execute();
}
catch(PDOException $e) {
die( _OP_ERROR($e->getMessage(), __FILE__ ,__LINE__) );
}
$QUERY_DAT = $stmt->fetchAll();
return empty($QUERY_DAT['value']) ? 0 : $QUERY_DAT['value'];
}
And this is line 1768:
$stmt = $dbh->prepare("SELECT * FROM stats_clicks WHERE typ=:typ AND user=:username AND data=:data LIMIT 1;");
I can't seem to find what is causing this. I use the $dbh-prepare(); statement in other functions in the same file.
$dbh is not defined at that line. Check where you create the object $dbh if it is before the line 1768 or it is not in any condition which is not fulfilled.
Try this :
Look at here
Probably the cause of your connection.
Feeling a little stupid to ask such a question, but this code block is driving me crazy.
function __construct() {
$db = new db();
$this->db = $db->pdo;
}
function getEmployeeDetails() {
$eid = $this->db->quote($this->eid);
try {
$sql = $this->db->query("
SELECT email, cnumber
FROM employees
WHERE EID = $eid
");
$r = $sql->fetch();
$this->email = $r[0];
$this->cnumber = $r[1];
}
catch (PDOException $e) {
throw new Exception("failed");
}
}
It doesn't throw an exception but fails inside the try block - "Call to a member function fetch() on a non-object".
var_dump of the statement object returns 'false'. Why?
I've tried running the query independently, inside MySql. It returns 1 row.
It's hard to tell whether you have done this, but PDO doesn't throw exceptions by default, except on connection failures. You have to specifically add this:
$this->db = $db->pdo;
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Without this, errors that occur during the query will cause ->query() to return false and that's obviously not an object that will have the ->fetch() method. You can also specify this attribute as part of the constructor call.
Also, you could use prepared statements instead of using ->quote():
$stmt = $this->db->prepare("SELECT email, cnumber
FROM employees
WHERE EID = ?");
$stmt->execute(array($this->eid));
$r = $stmt->fetch();
So I'm writing a PHP class called article and it has a bunch of methods like insert, delete and update. I have 3 other functions that follow the same code and they all work so I don't know why I am getting this error. Here is the code I wrote.
public function update(){
//make sure that the article does have an I.D
if(is_null($this->id)) trigger_error("Article::update(): Attempt to update an Article object that does not have its ID property set.", E_USER_ERROR );
//If there are any PDO errors they will be caught.
try{
$connection1 = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$connection1->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$sqlQuery = "UPDATE articles SET lastEditDate=FROM_UNIXTIME(:lastEditDate), lastEditUser=:lastEditUser, title=:title, content=:content WHERE id = :id";
$statement->prepare($sqlQuery);
$statement->bindValue(":lastEditDate", $this->lastEditDate, PDO::PARAM_INT);
$statement->bindValue(":lastEditUser", $this->lastEditUser, PDO::PARAM_STR);
$statement->bindValue(":title", $this->title, PDO::PARAM_STR);
$statement->bindValue(":content", $this->content, PDO::PARAM_STR);
$statement->bindValue(":id", $this->id, PDO::PARAM_INT);
$statement->execute();
$connection1 = null;
}
catch(PDOException $e){
echo "update():I'm sorry, Dave. I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
}
I read that you can get it from previous queries so I tried renaming and setting a bunch of the variables to null. I also checked the other threads I could find from this site and other and almost all of them were scope issues, which I don't think is the problem here since all my other functions work. Is there something painfully obvious that I'm missing?
It should be $connection1->prepare(), not $statement->prepare().