Os i'm starting to use mysqli, i'm getting a little confused with how it works.
So i have a function:
function verify_payment_date()
{
$today = date("Y-m-d");
$email = $_SESSION['email'];
$result = $this->conn->query("SELECT * FROM user WHERE email=$email");
while ($row = $result->fetch_object())
{
$next_payment_date = $row['next_payment_date'];
}
}
To set up my connect i do this in the same class:
private $conn;
function __construct()
{
$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database.');
}
can anyone give me a helping hand here because i'm totally lost. I was basing some of the code on this website:
http://www.willfitch.com/mysqli-tutorial.html
Also the error i'm getting is:
Fatal error: Call to a member function fetch() on a non-object in /home/vhosts/tradingeliteclub.com/subdomains/test/httpdocs/FES/members/classes/Mysql.php on line 52
I'm not sure where to go from here.
Thanks for your time and help.
$result is not mysql result, your query failed. Try
$result = $this->conn->query("SELECT * FROM user WHERE email='$email'");
// apostrophes
instead.
$this->conn->query returns resource on success, false on fail. You can avoid the error this way
if($result) while ($row = $result->fetch_object())
{
$next_payment_date = $row['next_payment_date'];
}
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()
I currently working on dashboard using PHP. I need to fetch data from database inside SQLyog, and transfer it into a graph. The problem is I keep getting this error; Fatal error: Call to undefined method MDB2_Error::execute() on line 30 in the class coding. The error is on $res = $query->execute($data); Can someone help me with my coding?
Here is the code for class.
<?php
class fetch_ranking extends MDB2{
var $con;
var $tbl_user;
var $tbl_isi_scopus_webo;
function fetch_ranking ($dsn) {
$this->con =& MDB2::singleton($dsn, $options=null);
//echo $this->con->getMessage();
if (PEAR::isError($this->con)) {
die($this->con->getMessage());
}
$this->tbl_user = 'user';
$this->tbl_isi_scopus_webo = 'ISI_SCOPUS_WEBO';
}
function fetch_webojuly16(){
$types = array();
$sql = "select university, criteria_rank as presence
from isi_scopus_webo
where month='july'
and year='2016'
group by university" ;
$query = $this->con->prepare($sql,$types,MDB2_PREPARE_RESULT);
$data = array();
$res = $query->execute($data);
if (PEAR::isError($res)) {
die($res->getMessage());
}
$this->con->setFetchMode(MDB2_FETCHMODE_ASSOC);
$valrec = $res->fetchAll();
return $valrec;
}
}?>
And this is for the graph.
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/config/siteconf.php');
require_once($basehome.'/config/default.php');
require_once($basedir.'/mod/ppsg/dsn.php');
require_once($basehome.'/mod/ppsg/class/fetch_data_from_db_isi_scopus_webo.php');
$current_year = date('Y', strtotime(date('Y')));
//$fhObj = new fetch_ranking($ranking);
$hostname="192.168.111.55";
$username="devopt";
$password="G0devopt$";
$dbname="ranking";
//Connect to the database
$connection = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
mysql_select_db($dbname, $connection)
or die("Could not select examples");
$xdata=array();
$ydata=array();
$xdata['name'] = 'PRESENCE';
$ydata['name'] = 'UNIVERSITY';
$ydata['color'] = '#ABEBC6';
//Call to a member function fetch_webojuly16() on a non-object
$webojuly16 = $fhObj->fetch_webojuly16();
foreach($webojuly16 as $wj16){
$xdata['data'][] = $wj16['presence'];
$ydata['data'][] = $wj16['university'];
}
$json_arr = array($xdata,$ydata);
print json_encode($json_arr, JSON_NUMERIC_CHECK);
?>
This is the coding for graph
The $this->con->prepare($sql,$types,MDB2_PREPARE_RESULT); call might return a MDB2_Error object in case the prepare() statement fails, as documented on http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodprepare. You have to check with PEAR::isError if that is the case or not. In your case it is, so you cannot call $res = $query->execute($data); on a MDB2_Error object, and that's exactly what the error message is telling you.
Add the if statement to check for errors on the $query variable and check the error messages you get.
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()
Good Afternoon!
I have made a connection class to a Microsoft Access Database (which works). However my problem lies where I'm trying to use this class to execute a simple SQL statement and I receive the error message: Fatal error: Call to a member function fetchALL() on a non-object.
I'm fairly new to PDO and have read a lot of articles online but to no avail. I think I understand my problem but not fully, please could someone shed some light on the situation and possibly provide an answer to why i'm getting the error message?
connectionClass.php
class connection{
public $con;
private $dbName;
function __construct(){
$this->dbName = $_SERVER["DOCUMENT_ROOT"] . "\database\yakety1new.mdb";
}
function connect(){
$this->con = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$this->dbName; Uid=Admin; Pwd=;");
$this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $this->con;
}
}
if (!ini_get('display_errors')) {
ini_set('display_errors', '1');
}
testIndex.php
try{
include_once '\classes\connectionClass.php';
$con = new connection();
$pdoConnection = $con->connect();
$sql = $pdoConnection->prepare("SELECT * FROM celebs");
$result = $pdoConnection->exec($sql);
while ($row = $result->fetchALL(PDO::FETCH_ASSOC)) {
echo $row['firstname'];
echo $row['surname'];
}
} catch (Exception $e){
echo 'ERROR:'.$e->getMessage();
file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND);
}
if (!ini_get('display_errors')) {
ini_set('display_errors', '1');
}
The error message is related to this line:
while ($row = $result->fetchALL(PDO::FETCH_ASSOC)) {
Any help is greatly appreciated, thanks!
$result is just a boolean that indicates whether the query was successful or not. The fetchAll method is on PDOStatement, so it should be:
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
You're also executing the statement wrong, it should be:
$result = $sql->execute();
The method you used is for executing a SQL string without first preparing it. You could instead do:
$result = $pdoConnection->exec("SELECT * FROM celebs");
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
ini_set('display_errors', '1');
include_once '\classes\connectionClass.php';
$con = new connection();
$pdoConnection = $con->connect();
$data = $pdoConnection->query("SELECT * FROM celebs")->fetchAll();
foreach ($data as $row) {
echo $row['firstname'];
echo $row['surname'];
}
this is all the code you need.
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);