Cannot fetch record using PHP and MySQL - php

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.

Related

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

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

How to pass connection varible in other php document

Help me with this code: I get this error.
Notice: Undefined variable: dbCon in C:\xampp\htdocs\Project\core\functions\general.php on line 5
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\Project\core\functions\general.php on line 5
Notice: Undefined variable: dbCon in C:\xampp\htdocs\Project\core\functions\Users.php on line 5
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\Project\core\functions\Users.php on line 5
Fatal error: Uncaught Error: Call to undefined function mysqli_result() in C:\xampp\htdocs\Project\core\functions\Users.php:8 Stack trace: #0 C:\xampp\htdocs\Project\login.php(4): user_exists(NULL) #1 {main} thrown in C:\xampp\htdocs\Project\core\functions\Users.php on line 8
Main folder(name -> PHP) has Index.php:
<?php
include 'core/init.php';
include 'includes/overall/header.php';
?>
PHP folder has Login.php:
<?php
include 'core/init.php';
if(user_exists('sudin') === true)
{
echo 'exists';
}
?>
under php/core folder init.php:
<?php
session_start();
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
?>
under php/core/database connect.php:
<?php
$dbCon=mysqli_connect('localhost','root','','project_point');
?>
under php/core/functions Users.php:
<?php
function user_exists($username)
{
$username = sanitize($username);
$query = mysqli_query($dbCon,"SELECT COUNT('Login_ID')FROM 'login' WHERE 'Username' = '$username'");
return(mysqli_result($query,0)==1) ? true : false;
}
?>
under php/core/functions general.php:
<?php
function sanitize($data)
{
return mysqli_real_escape_string($dbCon,$data);
}
?>[enter image description here][1]
Sorry for the messy way, here is the treeview:
Thankful for the help
There are a few things wrong here.
Firstly, you have a variable scope issue and you're also using the wrong identifier qualifiers in your query being regular quotes:
So, remove the quotes for this:
SELECT COUNT('Login_ID')FROM 'login' WHERE 'Username'
^ ^ ^ ^ ^ ^ Remove those
or use ticks:
SELECT COUNT(`Login_ID`) FROM `login` WHERE `Username`
Checking for errors on it using mysqli_error($dbCon) http://php.net/manual/en/mysqli.error.php would have thrown you something about it once it would have fired.
Make your connection global in your user_exists() function
global $dbCon;
Read up on both:
Identifier qualifiers http://dev.mysql.com/doc/en/identifier-qualifiers.html
Variable scope http://php.net/manual/en/language.variables.scope.php
The connection variable is not defined in the function scope. The hotfix is to add it with the "global" construct.
function user_exists($username)
{
global $dbCon;
...
you are trying to use a local variable $dbCon inside the function user_exists.
you can just change that variable to be global
ex:
under php/core/database connect.php:
<?php
global $dbCon;
$dbCon=mysqli_connect('localhost','root','','project_point');
?>
under php/core/functions Users.php:
<?php
function user_exists($username)
{
global $dbCon;
$username = sanitize($username);
$query = mysqli_query($dbCon,"SELECT COUNT('Login_ID')FROM 'login' WHERE 'Username' = '$username'");
return(mysqli_result($query,0)==1) ? true : false;
}
?>
The issue is that $dbCon is not defined in the scope of any function.
You could do 3 things:
function user_exists($username){
$query = mysqli_query($GLOBALS['dbCon'] ...
function user_exists($username){
global $dbCon;
$query = mysqli_query($dbCon ...
However, using globals in functions like this is usually a bad coding style.
I would recommend doing something like the following:
function getconn(){
static $conn;
if(!isset($conn)){
$conn = new mysqli_connect(...);
}
return $conn;
}
function user_exists($username){
$query = mysqli_query(getconn() ...
I was just about to add the issues with your SQL syntax, but Fred beat me to it. I think you want backticks ` instead, not '.

PHP include within wordpress not connecting to an external database

I am including a PHP page on a wordpres post with a wordpress plugin, the code on my included page is:
$conn=mysql_connect("localhost","username","pass");
mysql_select_db("dbname",$conn);
if(!function_exists("ContactLookup")) {
function ContactLookup($sequence) {
global $conn;
$sql="SELECT * from contacts where sequence = '".$sequence."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$result=mysql_fetch_array($rs);
return $result;
}
}
but its returning error:
Warning: mysql_query() expects parameter 2 to be resource, null given in index.php on line 93
line 93 = $rs=mysql_query($sql,$conn) or die(mysql_error());
Im not too sure why i receive this error because i have put $conn as a global variable in the PHP function and i have tested the database connection which works fine
rename the $conn variable to something else.
check this example:
$mysqlConn = null;
function ConnectToMysql() {
$mysqlConn=mysql_connect("localhost","username","pass") or die(mysql_error());
mysql_select_db("dbname",$mysqlConn) or die(mysql_error());
}
if(!function_exists("ContactLookup")) {
function ContactLookup($sequence) {
global $mysqlConn;
if(!$mysqlConn) ConnectToMysql(); // reconnect and reinit connection variable if somewhere it have been changed
$sql="SELECT * from contacts where sequence = '".$sequence."' ";
$rs=mysql_query($sql,$mysqlConn) or die(mysql_error());
$result=mysql_fetch_array($rs);
return $result;
}
}
P.S. I know my answer is not brilliant. I not fond of using mysql_* commands. but that's a quick fix.

Magento: How to read directly from Magento database

I'm trying to read directly from the Magento database through a custom script that looks like this:
require_once 'app/Mage.php';
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$conn = Mage::getSingleton('core/resource')->getConnection('core_read');
echo var_dump($conn);
function getAitocAttr() {
$test = $conn->fetchAll("SELECT * FROM customer_entity");
var_dump($test);
}
getAitocAttr();
Nothing is showing up when I run this script. What am I doing wrong? The error I'm receiving is:
Fatal error: Call to a member function fetchAll() on a non-object
Thanks
Looking at your error message
Fatal error: Call to a member function fetchAll() on a non-object
PHP is complaining about a method call to fetchAll on a non-object. Looking at your code, the only place you call fetchAll is here.
function getAitocAttr() {
$test = $conn->fetchAll("SELECT * FROM customer_entity");
var_dump($test);
}
Within the getAitocAttr function there's no $conn variable defined. When you say
$conn = Mage::getSingleton('core/resource')->getConnection('core_read');
you've defined $conn outside the scope of the getAitocAttr function. You'll need to either define $conn inside getAitocAttr, or declare $conn as global inside getAitocAttr for this to work.
I'm not sure what the problem with your script is exactly. It looks OK however I have tackled the problem slightly differently to this and it works for me.
require_once 'app/Mage.php';
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$conn = Mage::getSingleton('core/resource')->getConnection('core_read');
echo var_dump($conn);
function getAitocAttr()
{
$sql = "SELECT * FROM customer_entity";
$result = $conn->query($sql);
echo "<pre>";
while ($row = $readresult->fetch()) {
print_r($row);
}
}
getAitocAttr();

PHP Fatal Error Call to Undefined Method...that I'm 99% sure is defined

session.php
include("database.php");
function addPOTW($subweek, $subtitle, $subcaption, $subsubmittedby)
{
global $database, $form;
/* Errors exist, have user correct them */
if ($form->num_errors > 0) {
return 1; // Errors with form
}
/* No errors, add the new POTW to the database */
else {
if ($database->addNewPOTW($subweek, $subtitle, $subcaption, $subsubmittedby, $subfile)) {
return 0; //Event signup added succesfully
} else {
return 2; //Event signup attempt failed
}
}
}
This is my function, "addPOTW", located in the file session.php (with useless parts redacted). For some reason, I keep getting the error message: "Fatal error: Call to undefined method MySQLDB::addNewPOTW()" even though it's defined right here:
database.php
class MYSQLDB {
function addNewPOTW($date, $title, $caption, $submitter, $filepath)
{
$q = "INSERT INTO `" . TBL_POTW . "` VALUES ('','$date','$title','$caption','$submitter','$filepath')";
return mysql_query($q, $this->connection);
}
}
I have other functions in session.php accessing functions in database.php using the $database variable in the exact same way, and they work perfectly fine. Any ideas why only this one function is being reported as undefined??
Because you are referring to $this, you would need to instantiate an object from that class and then call the method.
Something like this should get it working...
$database = new MYSQLDB;
Make sure you have it in scope before your addPOTW() function.

Categories