This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 8 years ago.
I'm getting this error only when I try connect to my localhost, but if i test on my web host, everything is running perfect.
The error i get is pointing on my $query = $dbh->query("SELECT * FROM video");
<?php
$query = $dbh->query("SELECT video_img FROM video");
while($r = $query->fetch(PDO::FETCH_OBJ)) {
echo $r->video_title;
}
?>
db connection
<?php
$user = "root";
$pass = "";
try {
$dbh = new PDO('mysql:host=localhost;dbname=streaming', $user, $pass);
foreach($dbh->query('SELECT * from video') as $row) {
//print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Any tips :)?
Thanks
Looking at the codes you posted, $dbh doesn't make sense since no PDO connection has be initialized:
Second, you are selecting column video_img, then accessing/fetching $r->video_title. This doesn't make sense also:
$dbh = new PDO('mysql:host=localhost;dbname=DATABASE_NAME', 'username', 'password');
$query = $dbh->query("SELECT video_img FROM video");
while($r = $query->fetch(PDO::FETCH_OBJ)) {
echo $r->video_img;
}
Related
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 2 years ago.
I receive this error:
Fatal error: Call to a member function fetch() on boolean in
C:\xampp\htdocs\repo\generator\model\database.php on line 34
When I run this code:
class database
{
private $user = 'root';
private $pass = '';
public $pdo;
public function connect() {
try {
$this->pdo = new PDO('mysql:host=localhost; dbname=generatordatabase', $this->user, $this->pass);
echo 'Połączenie nawiązane!';
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone: ' . $e->getMessage();
}
}
public function createTable() {
$q = $this->pdo -> query('SELECT * FROM article');
while($row = $q->fetch()) {
echo $row['id'].' ';
}
$q->closeCursor();
}
}
?>
As per the PHP manual for PDO::query
PDO::query() returns a PDOStatement object, or FALSE on failure.
It looks like your query is failing (on line 33) and thus returning a BOOLEAN (false), likely because at that point in execution, PDO has not connected to a database that contains a table called article. In the connect() method I see that it tries to connect to a db called 'generatordatabase'; ensure this connection is being made prior to calling createTable(), otherwise ensure that it contains a table called 'article'.
I would recommend adding some more code examples, for instance the code that calls this class/method before the error is triggered.
Some error handling will help you avoid issues like this:
$q = $this->pdo->query('SELECT * FROM article');
//error case
if(!$q)
{
die("Execute query error, because: ". print_r($this->pdo->errorInfo(),true) );
}
//success case
else{
//continue flow
}
I'm not sure wheatear this is exactly the error I struggled with, but my error was due to my $con variable, I used a single $con for 2 SQL statements, for example:
$con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";
$stm = $con->prepare($sql);
$stm->execute();
and
$sql1 = "INSERT INTO posts
VALUES('$email','$body')";
$stm1 = $con->prepare($sql1);
if ($stm1->execute()) {
I should have done:
$con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";
$stm = $con->prepare($sql);
$stm->execute();
and
$con1 = new mysqli($host,$username,$password,$database);
$sql1 = "INSERT INTO posts
VALUES('$email','$body')";
$stm1 = $con1->prepare($sql1);
$stm1->execute()
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
This is my sql connection code
$config['db'] = array('host' => 'localhost', 'username' => 'root', 'password' => '', 'dbname' => 'reputize');
try
{
$db = new PDO('mysql:host='.$config['db']['host'].';dbname'.$config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
echo "Database connected successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
and this is the code i am using to fetch data from the table
$query = $db->query("select * from metaTags where filename='index'");
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
$ptitle=$row['MetaTitle'];
$desc=$row['MetaDisc'];
$kwords=$row['MetaKwd'];
}
but the error keeps on showing
Call to a member function query() on a non-object in C:\xampp\htdocs\template OOP\include\class\websiteClasses.php on line 14
I have tried many solutions here and on other sites as well but of no use.
Please help me out with this problem
you have an error here dbname'.$config['db']['dbname'] it should be dbname='.$config['db']['dbname']
You forget to add '=' after dbname.
Your config should look like below
dbname='.$config['db']['dbname']
From your comment, I understand that your '$db' variable must be declared accessible to other functions. Please check $db has valid database connection before query the database.
I usually use below code for connecting and getting data for my play projects.
function getDbConnection()
{
$pdo = null;
try
{
$pdo = new PDO("mysql:host=" . HOST . ";dbname=" . DBNAME,USERNAME,PWD);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $pe)
{
die("Sorry! Could not connect to database " . DBNAME. ": " . $pe->getMessage());
}
return $pdo;
}
function getData($qry)
{
$res = null;
try
{
if(!empty($qry))
{
$pdo = getDbConnection();
if(!empty($pdo))
{
$res = $pdo->query($qry);
}
}
}
catch(PDOException $pe)
{
throw $pe;
}
return $res;
}
Note: The above functions are not robust. But It works.
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
i am trying to fetch product list from mysql table. I am trying the following code but it is not working. Any suggestions please.
Fatal error: Call to undefined method mysqli_stmt::rowCount()
Code
$query = "SELECT id, name, price FROM female_products ORDER BY name";
$stmt = $con->prepare( $query );
$stmt->execute();
$num = $stmt->rowCount();
if($num>0)
{
//my work here
}
Config.php
$db_username = 'root';
$db_password = '';
$db_name = 'ecommerce';
$db_host = 'localhost';
try {
$con = new mysqli($db_host, $db_username, $db_password,$db_name);
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
Assuming you want a real PDO solution, rather then a mysqli one:
try {
$aOptions = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
// play around with options
$dbh = new PDO('mysql:host='.DBHOST.';dbname='.DBNAME.';charset=utf8', ''.DBUSER.'', ''.DBPWD.'',$aOptions);
}
catch(PDOException $e) {
echo $e->getMessage();
// do something smarter then just echo error!
}
$sql = "SELECT id, name, price FROM female_products ORDER BY name";
$stmt = $dbh->query($sql);
$aArray = $stmt->fetchAll();
if(count($aArray) > 0){
// do something
}
else{
// empty result
}
I personally think PDO is a much easier style then mysqli.
Options: you certainly gonna play with it soon, so it is handy to use an array for it.
You have used prepare,but yo do not make use of a prepared statement yet??
If this code works, try to find out hoe prepared statements work: one of the best defenses against SQL attacks!!
For configuration i used constants, so you need to define theme in your config. Constants, because they will never change during execution of your script!
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 2 years ago.
I receive this error:
Fatal error: Call to a member function fetch() on boolean in
C:\xampp\htdocs\repo\generator\model\database.php on line 34
When I run this code:
class database
{
private $user = 'root';
private $pass = '';
public $pdo;
public function connect() {
try {
$this->pdo = new PDO('mysql:host=localhost; dbname=generatordatabase', $this->user, $this->pass);
echo 'Połączenie nawiązane!';
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone: ' . $e->getMessage();
}
}
public function createTable() {
$q = $this->pdo -> query('SELECT * FROM article');
while($row = $q->fetch()) {
echo $row['id'].' ';
}
$q->closeCursor();
}
}
?>
As per the PHP manual for PDO::query
PDO::query() returns a PDOStatement object, or FALSE on failure.
It looks like your query is failing (on line 33) and thus returning a BOOLEAN (false), likely because at that point in execution, PDO has not connected to a database that contains a table called article. In the connect() method I see that it tries to connect to a db called 'generatordatabase'; ensure this connection is being made prior to calling createTable(), otherwise ensure that it contains a table called 'article'.
I would recommend adding some more code examples, for instance the code that calls this class/method before the error is triggered.
Some error handling will help you avoid issues like this:
$q = $this->pdo->query('SELECT * FROM article');
//error case
if(!$q)
{
die("Execute query error, because: ". print_r($this->pdo->errorInfo(),true) );
}
//success case
else{
//continue flow
}
I'm not sure wheatear this is exactly the error I struggled with, but my error was due to my $con variable, I used a single $con for 2 SQL statements, for example:
$con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";
$stm = $con->prepare($sql);
$stm->execute();
and
$sql1 = "INSERT INTO posts
VALUES('$email','$body')";
$stm1 = $con->prepare($sql1);
if ($stm1->execute()) {
I should have done:
$con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";
$stm = $con->prepare($sql);
$stm->execute();
and
$con1 = new mysqli($host,$username,$password,$database);
$sql1 = "INSERT INTO posts
VALUES('$email','$body')";
$stm1 = $con1->prepare($sql1);
$stm1->execute()
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
I have been trying to pull all infomation where $user is equal to subscriberID in my sql database. I am using the PDO method of inserting data and wish to use the query function also.
i am getting the following error message back from my try condition.
Fatal error: Call to a member function setFetchMode() on a non-object
I have considered maybe the problem has been caused by the method i use to pull the data as im fairly new to PDO.(i include a top.php that establishes the link to the database)
Thank you for your suggestions
<?php
include "top.php";
try{
$user = $_SESSION['login'];
echo "Welcome <strong>$user</strong> to your saved holidays";
//$getSavedHolidays = $db->query("SELECT * FROM saved_holidays WHERE subscriberID='$user'");
//preparing a PDO statment for accessing saved holidays when the logged in user matchs the subscriberID
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$getSavedHolidays = $db->prepare("SELECT * FROM saved_holidays WHERE subscriberID=:user");
//uses a bind valu as this makes the statment more secure
$getSavedHolidays->bindValue(":user", $_SESSION['login']);
$getsavedHolidays->setFetchMode(PDO::FETCH_ASSOC);
$getSavedHolidays->execute();
foreach ($Result as $row)
{
echo "<p><a href'".$row['link']."'>".$row['title']."</a><br \>" .
$row['description'] . "<br \>" .
$row['pubDate'] ."<br \></p>";
}
}
catch (PDOException $e)
{
print_r($e->errorInfo);
die();
}
?>
You should be preparing your statement. It has a nice added bonus of being more secure, plus it will solve your problem.
$user = $_SESSION['login'];
try {
$db = new PDO("mysql:host=localhost;dbname=database", "user", "pass");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$getSavedHolidays = $db->prepare("SELECT * FROM saved_holidays WHERE subscriberID=:user");
$getSavedHolidays->bindValue(":user", $_SESSION['login']);
$getSavedHolidays->setFetchMode(PDO::FETCH_ASSOC);
$getSavedHolidays->execute();
$Result = $getSavedHolidays->fetchAll();
foreach ($Result as $row) {/*...*/}
}
catch (PDOException $e) {
print_r($e->errorInfo);
die();
}
EDIT
You have an error in the code you've pasted above:
$$getSavedHolidays = $db->prepare("SELECT * FROM saved_holidays WHERE subscriberID=:user");
Should be
$getSavedHolidays = $db->prepare("SELECT * FROM saved_holidays WHERE subscriberID=:user");
there is explicit syntax error. mussing closing single quote:
$getSavedHolidays = $db->query("SELECT * FROM saved_holidays WHERE subscriberID='$user'");
and by the way, since you're using PDO it's more safe to use bindValue function to pass values to SQL request.