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 '.
Related
I am having an issue with an include file accessing another include file (my db connection)
I have a site with the following layout ::
root/conn.php :: db connection file
root/site/file1.php :: regular page
root/site/include/func.inc :: file with functions in it
Each file is listed below with appropriate code...
conn.php ::
<?php
$host = 'localhost';
$db = 'mydb';
$user = 'myuser';
$pass = 'mypass';
$charset = 'utf8mb4';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$conn = new mysqli($host, $user, $pass, $db);
$conn->set_charset($charset);
} catch (\mysqli_sql_exception $e) {
throw new \mysqli_sql_exception($e->getMessage(), $e->getCode());
}
unset($host, $db, $user, $pass, $charset);
?>
file1.php ::
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
include_once ("{$_SERVER['DOCUMENT_ROOT']}/site/include/func.inc");
{ code that calls functions in func.php }
func.inc ::
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
{ various functions }
When I browse to /file1.php, I get the following error ::
PHP Notice: Undefined variable: conn in C:\inetpub\root\site\include\func.inc on line 231
PHP Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\inetpub\root\site\include\func.inc:231
my func.inc file cannot seem to find the conn.php file. I have also tried removing the include function from func.inc. There are other files in the /include folder that can access the conn.php file with the same include function.
The issue relates to something called the variable scope (https://www.php.net/manual/en/language.variables.scope.php)
==> Please read that to get detailed information
The second example describes your problem
func.inc
<?php
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
// to illustrate the issue, the include can be simplified to
// $conn = "something"; // => global scope variable
function myFunc(){
echo $conn; //no output - $conn exists ONLY in the local scope --> not available inside thisfunction
}
Solution 1:
func.inc
<?php
function myFunc($conn){
echo $conn; //outputs $conn
}
file1.php
<?php
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
include_once ("{$_SERVER['DOCUMENT_ROOT']}/site/include/func.inc");
//call function and pass the $conn, it's available here in the global scope
myFunc($conn);
Solution 2
but keep in mind global is considered as bad practice
func.inc
<?php
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
function myFunc(){
global $conn; //$conn is declared global in the local scope of this function
echo $conn; //outputs $conn from conn.php if you call myFunc from anywhere
}
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 4 years ago.
like my title says, whenever I try to use my variables from another php file, it doesn't work (Undefined variable).
I did declare them in the file that I'm including.
For example, I have this file called variables.php that have this in it:
<?php
$DEBUG = TRUE;
$mysqli = new mysqli("127.0.0.1", "root", "", "29185917-database");
$DEBUG_LOG_FILE = "../log";
?>
And then I have another file called debug.php that tries to use the variable 'DEBUG' but it cannot access it. Here is my debug.php file:
<?php
require_once 'variables.php';
function echo_debug(string $message)
{
if($DEBUG) {
echo $message;
}
}
?>
Whenever I try to use my function echo_debug I get the error message :
Undefined variable 'DEBUG'.
Any help on this problem is appreciated :).
Functions have their own scope. The variable is accessible, just not from inside the function.
You could pass $DEBUG as a parameter
function echo_debug(string $message, bool $DEBUG)
Then you would call it as
echo_debug("comment that will help me debug in dev mode", $DEBUG);
Another option is to declare DEBUG as a constant,
define('DEBUG', true);
$mysqli = new mysqli("127.0.0.1", "root", "", "29185917-database");
$DEBUG_LOG_FILE = "../log";
Then, in your function you would check for that constant:
function echo_debug(string $message) {
if(DEBUG) { ... }
}
You could also use the global keyword, right above your if(), try to add global $DEBUG;.
require_once 'variables.php';
function echo_debug(string $message)
{
global $DEBUG;
if($DEBUG) { ... }
}
But generally the other two solutions are better, global variables are sometimes frowned upon.
As per my comment, you can also use a constant and avoid the variable issue altogether.
<?php
define('DEBUG', true);
$mysqli = new mysqli("127.0.0.1", "root", "", "29185917-database");
$DEBUG_LOG_FILE = "../log";
?>
Then in the function check if the constant has been defined
<?php
require_once 'variables.php';
function echo_debug(string $message) {
if (defined('DEBUG') && DEBUG === true) {
echo $message;
}
}
?>
do like this:
function echo_debug(string $message,$data)
{
if($data === TRUE) {
echo $message;
}
}
call function:
require_once 'variables.php';
$message = "comment that will help me debug in dev mode";
$output = echo_debug($message,$DEBUG);
print_r($output);
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.
i am having some troubles my the "real_escape_string" and i need some help
login.php
<?php include('Connections/local.php'); ?>
<?php
function GetSQLValueString($sql) {
$sql = $mysqli->real_escape_string($sql);
return $sql;
}
?>
local.php
<?php
$hostname_local = "xxx";
$database_local = "xxx";
$username_local = "xxx";
$password_local = "xxx";
$mysqli = new mysqli($hostname_local, $username_local, $password_local, $database_local);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
the error is
Undefined variable: mysqli
i've tried some things ( like moving the content of the local.php inside the login.php ) but nothing works
You can't access $mysqli inside your function.
If you want to, add global $mysqli; in your function to make it accessible. Alternatively, you could pass the $mysqli as a parameter.
Why not just use the function call directly.
My suggestion, just create a simpler (and easier to read function) called "esc" and use that anytime you need to escape anything sql related.
function esc($string, $mysqli = false) {
if (!$mysqli) global $mysqli;
return mysqli_real_escape_string($mysqli,$string);
}
And then just use this by doing the following:
$sql = esc($string); //if $mysqli is already set globally, and thus will be inherited by the function
OR
$sql = esc($string,$mysqli); //if $mysqli is to be passed into each func call
Below is my class. Fig A
<?php
class qcon{
public static $conn;
function dbcon()
{
if (!$conn)
{
$host = 'x';
$username = 'x';
$password = 'x';
$dbname = 'x';
$conn = mysqli_connect($host , $username , $password ,$dbname);
}
return $conn;
}
}
?>
Which is called here. Fig B
require_once(class file above);
function openSesame()
{
$boogey = new qcon();
$conn = $boogey->dbcon();
if (!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
Is causing
Notice: Undefined variable: conn in C:\...\xxxx\figAclass.php on line 10
I know I can simply turn errors off, but this seems unwise. I took a look at a generic SO question about the undefined variable notice. Obviously the advice was general - use isset. Had a go at isset and this does not seem correct for what I am trying to do.
Based on the code in figure A and B, is there anything obvious causing the notice to be flagged up. Could you demonstrate a fix that is in line with the existing code shown.
Don't use if (!$conn), which will check to see if the variable is true/false or contains a value, not if it's defined. Use this instead:
if(empty($conn))
This checks to see if the variable is defined, and if it is NULL/empty.
You also want to use $this->conn inside of your class instead, since you're defining it as a variable of the class.
Like I said in my comment above, since you have a static $conn, you need to refer to it like:
public function dbconn()
{
if (!self::$conn) {
// blah
}
return self::$conn;
}
Your error is happening because you're attempting to reference a variable named $conn, but due to scope, no such thing exists.
when you access it, you should use $this->conn, in example:
if(!$this->conn){...}
edited read the question too fast, sorry
You can't use if (!$conn)for this because that will only return 'true' or 'false'.
Use:
if empty($conn) instead.