Warning: mysqli_query(): Couldn't fetch mysqli in <file> on line <number> - php

The view file
<?php
require('OrderModel.php');
session_start();
if(!isset($_SESSION['orderModel'])){
$newModel = new OrderModel();
$_SESSION['orderModel'] = $newModel;
} else{
$newModel = $_SESSION['orderModel'];
}
$newModel->addToBasket(1, 30);
echo $newModel->getItemName($newModel->basket[0][0]);
?>
The OrderModel file (simplified)
class OrderModel{
public $basket;
public $orderDate;
public $orderTime;
public $sent;
public $dbc;
public $customerOrderID;
public function __construct()
{
$this->dbc = require_once('../../db/config.php');
$this->basket = [];
}
public function addToBasket($itemNumber, $itemQuantity){
array_push($this->basket, [$itemNumber, $itemQuantity]);
}
public function getItemName($itemNum){
$query = "SELECT ItemName FROM item WHERE ItemID = $itemNum;";
$r = mysqli_query($this->dbc, $query); //Line 31
if($r){
return mysqli_fetch_row($r)[0];
}else{
echo mysqli_error($this->dbc); //Line 35
}
}
I can confirm that the config.php file is definitely configured correctly and is talking to the DB. In any rate, the code is:
<?php
define ('username', 'root');
define ('password', 'root');
define ('server', '127.0.0.1');
define ('database', 'alberto');
$dbc = mysqli_connect(server, username, password, database) OR DIE ('Could not connect to MySQL: ' . mysqli_connect_error());
mysqli_set_charset($dbc, 'utf8');
return $dbc;
?>
I am getting the following error messages from the view file:
Warning: mysqli_query(): Couldn't fetch mysqli in D:\UniServerZ\www\alberto\app\models\OrderModel.php on line 31
Warning: mysqli_error(): Couldn't fetch mysqli in D:\UniServerZ\www\alberto\app\models\OrderModel.php on line 35
I suspect the error is to do with the session, but I can't seem to find any answers from the threads posted so far.
Please kindly advise. Thank you.

Barmar is correct that $this->dbc is not a valid mysqli object. You are using the require_once with the file like a function. Make the config.php a class, and make the db connection from there. See here for an example of what I'm referring to. https://gist.github.com/jonashansen229/4534794

Related

main(): Couldn't fetch mysqli_stmt in line 31 if ($stmt->num_rows > 0) [duplicate]

Warning: mysqli::query(): Couldn't fetch mysqli in C:\Program Files (x86)\EasyPHP-DevServer-13.1VC9\data\localweb\my portable files\class_EventCalendar.php on line 43
The following is my connection file:
<?php
if(!isset($_SESSION))
{
session_start();
}
// Create array to hold error messages (if any)
$ErrorMsgs = array();
// Create new mysql connection object
$DBConnect = #new mysqli("localhost","root#localhost",
NULL,"Ladle");
// Check to see if connection errno data member is not 0 (indicating an error)
if ($DBConnect->connect_errno) {
// Add error to errors array
$ErrorMsgs[]="The database server is not available.".
" Connect Error is ".$DBConnect->connect_errno." ".
$DBConnect->connect_error.".";
}
?>
This is my class:
<?php
class EventCalendar {
private $DBConnect = NULL;
function __construct() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
function __destruct() {
if (!$this->DBConnect->connect_error) {
$this->DBConnect->close();
}
}
function __wakeup() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
// Function to add events to Zodiac calendar
public function addEvent($Date, $Title, $Description) {
// Check to see if the required fields of Date and Title have been entered
if ((!empty($Date)) && (!empty($Title))) {
/* if all fields are complete then they are
inserted into the Zodiac event_calendar table */
$SQLString = "INSERT INTO tblSignUps".
" (EventDate, Title, Description) ".
" VALUES('$Date', '$Title', '".
$Description."')";
// Store query results in a variable
$QueryResult = $this->DBConnect->query($SQLString);
I'm not great with OOP PHP and I'm not sure why this error is being raised. I pulled this code from elsewhere and the only thing I changed was the #new mysqli parameters. Can anyone help me to understand what is going wrong?
Probably somewhere you have DBconnection->close(); and then some queries try to execute .
Hint: It's sometimes mistake to insert ...->close(); in __destruct() (because __destruct is event, after which there will be a need for execution of queries)
Reason of the error is wrong initialization of the mysqli object. True construction would be like this:
$DBConnect = new mysqli("localhost","root","","Ladle");
I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.
$db_connection = new mysqli("127.0.0.1","root","","db_name");
Check if db name do not have "_" or "-"
that helps in my case

Warning: mysqli::query(): Couldn't fetch mysqli in D:\wamp\www\site\admin\list.php on line 54 [duplicate]

Warning: mysqli::query(): Couldn't fetch mysqli in C:\Program Files (x86)\EasyPHP-DevServer-13.1VC9\data\localweb\my portable files\class_EventCalendar.php on line 43
The following is my connection file:
<?php
if(!isset($_SESSION))
{
session_start();
}
// Create array to hold error messages (if any)
$ErrorMsgs = array();
// Create new mysql connection object
$DBConnect = #new mysqli("localhost","root#localhost",
NULL,"Ladle");
// Check to see if connection errno data member is not 0 (indicating an error)
if ($DBConnect->connect_errno) {
// Add error to errors array
$ErrorMsgs[]="The database server is not available.".
" Connect Error is ".$DBConnect->connect_errno." ".
$DBConnect->connect_error.".";
}
?>
This is my class:
<?php
class EventCalendar {
private $DBConnect = NULL;
function __construct() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
function __destruct() {
if (!$this->DBConnect->connect_error) {
$this->DBConnect->close();
}
}
function __wakeup() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
// Function to add events to Zodiac calendar
public function addEvent($Date, $Title, $Description) {
// Check to see if the required fields of Date and Title have been entered
if ((!empty($Date)) && (!empty($Title))) {
/* if all fields are complete then they are
inserted into the Zodiac event_calendar table */
$SQLString = "INSERT INTO tblSignUps".
" (EventDate, Title, Description) ".
" VALUES('$Date', '$Title', '".
$Description."')";
// Store query results in a variable
$QueryResult = $this->DBConnect->query($SQLString);
I'm not great with OOP PHP and I'm not sure why this error is being raised. I pulled this code from elsewhere and the only thing I changed was the #new mysqli parameters. Can anyone help me to understand what is going wrong?
Probably somewhere you have DBconnection->close(); and then some queries try to execute .
Hint: It's sometimes mistake to insert ...->close(); in __destruct() (because __destruct is event, after which there will be a need for execution of queries)
Reason of the error is wrong initialization of the mysqli object. True construction would be like this:
$DBConnect = new mysqli("localhost","root","","Ladle");
I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.
$db_connection = new mysqli("127.0.0.1","root","","db_name");
Check if db name do not have "_" or "-"
that helps in my case

Cannot fetch record using PHP and MySQL

I am unable to fetch record from a MySQL database using PHP. Here is my code.
user.php:
require_once ('../../include/dbconfig.php');
require_once ('common.php');
error_reporting(E_ALL);
ini_set('display_errors', '1');
$userClass=new CommonConnectorFuncs();
$redata=$userClass->insertUserRecordForSignup();
echo $redata;exit;
common.php:
require_once ('../../include/dbconfig.php');
error_reporting(E_ALL);
ini_set('display_errors', '1');
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") ? "https" : "http";
$imagepath=$protocol. "://" . $_SERVER['HTTP_HOST']."/connector/upload/";
class CommonConnectorFuncs{
function __construct() {
}
// destructor
function __destruct() {
// $this->close();
}
public function insertUserRecordForSignup(){
$sql=mysqli_query($connect,"select * from cn_user_info order by user_id desc");
while ($row=mysqli_fetch_array($sql)) {
$data[]=$row;
}
return $data;
}
}
Here I am trying to fetch record and print through class but it's throwing the below message.
Notice: Undefined variable: connect in common.php on line 16
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in common.php on line 16
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in common.php on line 17
Notice: Undefined variable: data in common.php on line 20
Those query is working fine inside the user.php file but it's not working in common.php file.
As mentioned in comments, this is a scoping issue. Specifically, $connect is not in scope.
Notice: Undefined variable: connect in common.php on line 16
where connect is not defined anywhere.
Moreover, It's exactly as the error states as you're passing arguments to mysqli_query incorrectly. Assumming $connect is your mysqli connection generated at some point by new mysqli() it should be:
$sql = "select * from cn_user_info order by user_id desc";
$result = mysqli_query( $connect,$sql) or die('Could not look up user information; ' . mysqli_error($connect))
Hope it helps!
Make the connect variable a property of your class as by parsing it in your construct function
require_once ('../../include/dbconfig.php');
require_once ('common.php');
error_reporting(E_ALL);
ini_set('display_errors', '1');
$userClass=new CommonConnectorFuncs($connect);
$redata=$userClass->insertUserRecordForSignup();
echo $redata;exit;
In your class,
class CommonConnectorFuncs{
var $Connection;
function __construct($connection) {
try{
if($connection != null){
$this->Connection = $connection;
}else{
throw new Exception('Connection is null. COuld not process further');
}
}catch(Exception $ex){
echo $ex->getMessage();
exit;
}
}
// destructor
function __destruct() {
// $this->close();
}
public function insertUserRecordForSignup(){
$sql=mysqli_query($this->Connection,"select * from cn_user_info order by user_id desc");
while ($row=mysqli_fetch_array($sql)) {
$data[]=$row;
}
return $data;
}
}
The problem is in that you are trying to access a global variable within a function.
First of all, make sure you include the php file with the relevant database connection. And as you are trying to access a global variable there are two ways to achieve this.
Method 1
Create a global variable at the top of the function.
global $connect;
But as Qirel says in this comment, it is a bad practise, so I'd suggest the next.
Method 2
Pass the connection to the function's parameters.
public function insertUserRecordForSignup($connect){
$sql=mysqli_query($connect,"select * from cn_user_info order by user_id desc");
while ($row=mysqli_fetch_array($sql)) {
$data[]=$row;
}
return $data;
}
Hope you find this useful.

Trying to connect from iOS to MySQL Database using php ( HTTP POST )

Below is my sample code for my PHP program, and my database has already been created.
createteam.php:
<?php
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//getting values
$teamName = $_POST['name'];
$memberCount = $_POST['member'];
//including the db operation file
require_once '../includes/DbOperation.php';
$db = new DbOperation();
//inserting values
if($db->createTeam($teamName,$memberCount)){
$response['error']=false;
$response['message']='Team added successfully';
}else{
$response['error']=true;
$response['message']='Could not add team';
}
}else{
$response['error']=true;
$response['message']='You are not authorized';
}
echo json_encode($response);
config.php:
<?php
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'iphone');
DbConnect.php:
<?php
class DbConnect
{
private $conn;
function __construct()
{
}
/**
* Establishing database connection
* #return database connection handler
*/
function connect()
{
require_once 'Config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// returing connection resource
return $this->conn;
}
}
DbOperation.php:
<?php
class DbOperation
{
private $conn;
function __construct()
{
require_once dirname(__FILE__) . '/Config.php';
require_once dirname(__FILE__) . '/DbConnect.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
//Function to create a new user
public function createTeam($name, $memberCount)
{
$stmt = $this->conn->prepare("INSERT INTO team(name, member) values(?, ?)");
$stmt->bind_param("si", $name, $memberCount);
$result = $stmt->execute();
$stmt->close();
if ($result) {
return true;
} else {
return false;
}
}
}
However when I use HTTP POST method using Postman in Chrome, it states this
Notice: Undefined index: name in D:\xampp\htdocs\TestServ\api\createteam.php on line 9
Notice: Undefined index: member in D:\xampp\htdocs\TestServ\api\createteam.php on line 10
Warning: mysqli::__construct(): (HY000/1049): Unknown database 'iphone' in D:\xampp\htdocs\TestServ\includes\DbConnect.php on line 20
Failed to connect to MySQL: Unknown database 'iphone'
Warning: mysqli::prepare(): Couldn't fetch mysqli in D:\xampp\htdocs\TestServ\includes\DbOperation.php on line 20
Fatal error: Uncaught Error: Call to a member function bind_param() on null in D:\xampp\htdocs\TestServ\includes\DbOperation.php:21 Stack trace: #0 D:\xampp\htdocs\TestServ\api\createteam.php(18): DbOperation->createTeam(NULL, NULL) #1 {main} thrown in D:\xampp\htdocs\TestServ\includes\DbOperation.php on line 21
What does this mean, and what should I change?
Your first two errors are caused because of these two lines:
$teamName = $_POST['name'];
$memberCount = $_POST['member'];
The error (Undefined index) tells you that you have some non-existing variables, in this case name and member from your $_POST[] variable. Make sure your POST request is correctly made, see undefined variable for more information.
Your third error (Warning: mysqli::__construct(): (HY000/1049)) is caused because there isn't a database called iphone in your database system. Check if you have typed it correctly or if you haven't yet created an actual database with the name iphone.
The last error is caused because of the first two errors, since name and member aren't (correctly) defined in your POST request they have been set to NULL and the mysqli library doesn't like that.

MYSQLI Error : Call to a member function execute() on a non-object [duplicate]

Warning: mysqli::query(): Couldn't fetch mysqli in C:\Program Files (x86)\EasyPHP-DevServer-13.1VC9\data\localweb\my portable files\class_EventCalendar.php on line 43
The following is my connection file:
<?php
if(!isset($_SESSION))
{
session_start();
}
// Create array to hold error messages (if any)
$ErrorMsgs = array();
// Create new mysql connection object
$DBConnect = #new mysqli("localhost","root#localhost",
NULL,"Ladle");
// Check to see if connection errno data member is not 0 (indicating an error)
if ($DBConnect->connect_errno) {
// Add error to errors array
$ErrorMsgs[]="The database server is not available.".
" Connect Error is ".$DBConnect->connect_errno." ".
$DBConnect->connect_error.".";
}
?>
This is my class:
<?php
class EventCalendar {
private $DBConnect = NULL;
function __construct() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
function __destruct() {
if (!$this->DBConnect->connect_error) {
$this->DBConnect->close();
}
}
function __wakeup() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
// Function to add events to Zodiac calendar
public function addEvent($Date, $Title, $Description) {
// Check to see if the required fields of Date and Title have been entered
if ((!empty($Date)) && (!empty($Title))) {
/* if all fields are complete then they are
inserted into the Zodiac event_calendar table */
$SQLString = "INSERT INTO tblSignUps".
" (EventDate, Title, Description) ".
" VALUES('$Date', '$Title', '".
$Description."')";
// Store query results in a variable
$QueryResult = $this->DBConnect->query($SQLString);
I'm not great with OOP PHP and I'm not sure why this error is being raised. I pulled this code from elsewhere and the only thing I changed was the #new mysqli parameters. Can anyone help me to understand what is going wrong?
Probably somewhere you have DBconnection->close(); and then some queries try to execute .
Hint: It's sometimes mistake to insert ...->close(); in __destruct() (because __destruct is event, after which there will be a need for execution of queries)
Reason of the error is wrong initialization of the mysqli object. True construction would be like this:
$DBConnect = new mysqli("localhost","root","","Ladle");
I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.
$db_connection = new mysqli("127.0.0.1","root","","db_name");
Check if db name do not have "_" or "-"
that helps in my case

Categories