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()
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:
mysqli query results to show all rows
(4 answers)
Closed 6 years ago.
I am trying for getting multiple records from database but when I try for more then one records. I always getting empty.
First I try FROM DbOperation.php:
public function getDayListByDate($DateString){
$stmt = $this->con->prepare("SELECT DateString FROM gk_eng WHERE DateString= ?");
$stmt->bind_param("s",$DateString);
$stmt->execute();
$result = $stmt->get_result();
return $result;
}
php data get
<?php
require_once 'DbOperation.php';
$db = new DbOperation();
$DateString = $_POST['DateString'];
$devices = $db->getDayListByDate($DateString);
$response = array();
$response['error'] = false;
$response['devices'] = array();
while($device = $devices->fetch_assoc()){
$temp = array();
$temp['Question']=$device['Question'];
$temp['Option_2']=$device['DateString'];
array_push($response['devices'],$temp);
}
echo json_encode($response);
Response: {"error":false,"devices":[{"Question":null,"Option_2":"10/1/2016 12:00:00 AM"},{"Question":null,"Option_2":"10/1/2016 12:00:00 AM"},{"Question":null,"Option_2":"10/1/2016 12:00:00 AM"}{"Question":null,"Option_2":"10/1/2016 12:00:00 AM"}]}
But when I trying for all records and change database query for getting Question field in reponse like.
public function getDayListByDate($DateString){
$stmt = $this->con->prepare("SELECT * FROM gk_eng WHERE DateString= ?");
$stmt->bind_param("s",$DateString);
$stmt->execute();
$result = $stmt->get_result();
return $result;
}
I am getting result empty like "".
I am using for connection
function connect()
{
//Including the constants.php file to get the database constants
include_once dirname(__FILE__) . '/Config.php';
//connecting to mysql database
$this->con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//finally returning the connection link
return $this->con;
}
I think the way you are binding is incorrect too:
public function getDayListByDate($DateString){
$stmt = $this->con->prepare("SELECT * FROM gk_eng WHERE DateString= :DS");
$stmt->bind_param(":DS",$DateString);
$stmt->execute();
$result = $stmt->fetchAll();
return $result;
}
Try This
function getDayListByDate($DateString) {
$result = $this->con->query("SELECT * FROM gk_eng WHERE DateString='$DateString' ");
return $result;
}
you can get answer.. if didnt get ans .. let me know
So I have this code
$lang=new language();
$default_language=$lang->getLanguage(0);
$currencies = new currency();
$currencies = $currencies->getCurrencies();
getCurrencies() and getLanguage() are in another file with classes.
public function getCurrencies() {
$curr=new record();
return $curr -> getRecords('currencyTable','currency_order',array("currency_id","currency_name"));
}
public function getLanguage($record) {
$lang=new record();
return $lang->getRecord('languageTable',$record,'lang_order','*');
}
And getRecords and getRecord are public functions it the record class
I keep on getting the error
Fatal error: Call to a member function prepare() on null
Referring to the query of the getRecords functions.
I dont know how to fix this. Does this has to do with the connection to the database?
Also, the weird part is that if I remove the
$lang=new language();
$default_language=$lang->getLanguage(0);
part, this error goes away. Any help? Is the error in the $default_language=$lang->getLanguage(0); line and this is why it is messing up the database connection, resulting to this error?
Thanks
EDIT
Here are the getRecord and getRecords
public function getRecords($table,$sorder,$field_names) {
$conn = db::open();
//- build string of field names
if($field_names!='*'){
$field_string="";
foreach ($field_names as $value) {
$field_string.=",".$value;
}
$field_string = substr($field_string,1);
}else{
$field_string='*';
}
//end up with field1, field2... or *
//soreder is a field, contains int like 1 2 3
//- run statement
$stmt = $conn->prepare("SELECT ".$field_string." FROM ".$table." ORDER BY ".$sorder." ASC");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
and
public function getRecord($table,$record,$sorder,$field_names) {
$conn = db::open();
if($field_names!='*'){
$field_string="";
foreach ($field_names as $value) {
$field_string.=",".$value;
}
$field_string = substr($field_string,1);
}else{
$field_string='*';
}
//same things for $field_string and $sorder
$stmt = $conn->prepare("SELECT ".$field_string." FROM ".$table." ORDER BY ".$sorder." LIMIT ? OFFSET ?");
$stmt->bindValue(1, 1 , PDO::PARAM_INT);
$stmt->bindValue(2, $record, PDO::PARAM_INT);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
return $results;
}
I fixed an error. In getRecord I had LIMIT 1 and I fixed it as above. I still get the same error about the getRecords line : $stmt = $conn->prepare("SELECT ".$field_string." FROM ".$table." ORDER BY ".$sorder." ASC");
Any thoughts?
Thanks
Your database connection failed. The error is not in your posted code. The error in your code is when the statement is being prepared.
Ex: $statement = $dbh->prepare("SELECT * FROM some_table"). I would recommend throwing an exception to see what's going wrong with your connection. You can do this by adding the options to your pdo initialization. array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
try{
$dbh = new PDO('mysql:host='.MYSQL_HOST.';dbname='.MYSQL_DB,
MYSQL_USERNAME,
MYSQL_PASSWORD,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}catch(Exception $e){
echo $e->getMessage();
}
Hope this helps
I'm trying to call my function, but she's wrong.
I believe it is in connection variable.
Connection:
$conn = mysqli_connect('','','', '');
if(mysqli_connect_errno()) {
header("Location: error.php");
exit();
}
Function:
function t_car($id) {
global $conn;
$s_t_car = "SELECT *
FROM t_car
WHERE session='$id'";
$s_t_car_return = mysqli_query($conn, $s_t_car) or die("Erro SQL.".mysqli_error());
return $s_t_car_return;
}
Call Function:
$s_t_car_return = t_car($conn, $_SESSION['session_client']);
if(mysqli_num_rows($s_t_car_return )!=0) {
while($r_t_car = mysqli_fetch_array($s_t_car_return )) {
}
}
Error:
Catchable fatal error: Object of class mysqli could not be converted to string
At first you need to enter your settings from your MySQL server (mysql db).
$connection = mysqli_connect("HOSTNAME","USERNAME", "PASSWORD","DATABASE");
You can then use an if statement to check if the connection to the server has been made, if so, continue execution of following code, otherwise die();
If you want to fetch the data see below here:
$res = $connection->query("SELECT finger FROM hand WHERE index = 3");
while($row = $res->fetch_array())
{
print_r($row);
}
mysqli_query() returns a result. You have to fetch the result to do something with it.
$res = mysqli_query($conn, $s_t_car) or die("...");
$s_t_car_return = mysqli_fetch_row($res);
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.