在我的Android应用中。我正在尝试对用户进行身份验证,因为我已经编写了一个php脚本来建立与数据库的连接,但不幸的是我收到了以下错误 -
"未定义的变量:con
要解决此错误,我已将 " $ con" 声明为全局变量,但仍会出现相同的错误 -
我的 db_connect.php 代码是---
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT
{
private $con;
// constructor
function __construct()
{
// connecting to database
$this->connect();
}
// destructor
function __destruct()
{
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect()
{
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// Selecing database
$db = mysqli_select_db($con, DB_DATABASE);
// returing connection cursor
return $con;
}
/*
* Function to close db connection
*/
function close()
{
// closing db connection
mysqli_close($con);
}
}
?>
请帮助。谢谢..!
答案 0 :(得分:0)
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT
{
private $con;
// constructor
function __construct()
{
// connecting to database
$this->connect();
}
// destructor
function __destruct()
{
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect()
{
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$this->con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// Selecing database
$db = mysqli_select_db($this->con, DB_DATABASE);
// returing connection cursor
return $this->con;
}
/*
* Function to close db connection
*/
function close()
{
// closing db connection
mysqli_close($this->con);
}
}
?>
使用$this->con
代替$con
,因为$con
是一个类变量,并且您将其用作本地变量。
答案 1 :(得分:0)
问题 - 函数$con
中的connect()
变量未将$con
的值赋给您给出的公共变量,同样地,在close()
函数中它没有引用公共变量。
将您的功能连接更改为 -
function connect()
{
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$this->con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// Selecing database
$db = mysqli_select_db($con, DB_DATABASE);
// returing connection cursor
return $con;
}
和函数close()as -
function close()
{
// closing db connection
mysqli_close($this->con);
}
最终守则 -
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT
{
private $con;
// constructor
function __construct()
{
// connecting to database
$this->connect();
}
// destructor
function __destruct()
{
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect()
{
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$this->con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// Selecing database
$db = mysqli_select_db($con, DB_DATABASE);
// returing connection cursor
return $con;
}
/*
* Function to close db connection
*/
function close()
{
// closing db connection
mysqli_close($this->con);
}
}
?>