Php 从MySQL更改为MySQLi。类中的Select INDER函数不起作用
这是一个简单的问题,但出于某种原因,我没有看到它。 我正在将一段代码从MySQL更改为MySQLi。问题是什么时候 我使用新的MySQLi代码,select不起作用 我展示了三段代码。 1-Index.php文件,包括代码 2.显示如何连接到数据库的Connect.php文件 3.使用失败函数的Redirect.php类代码 在底部的Redirect.php中,我包含了可以工作的旧代码 新代码不起作用。我所看到的区别是新的 代码使用$con与数据库通信,我尝试了全局$con和 它也失败了。求你了,我需要你的帮助。你能告诉我我做错了什么吗。 谢谢Php 从MySQL更改为MySQLi。类中的Select INDER函数不起作用,php,mysql,mysqli,Php,Mysql,Mysqli,这是一个简单的问题,但出于某种原因,我没有看到它。 我正在将一段代码从MySQL更改为MySQLi。问题是什么时候 我使用新的MySQLi代码,select不起作用 我展示了三段代码。 1-Index.php文件,包括代码 2.显示如何连接到数据库的Connect.php文件 3.使用失败函数的Redirect.php类代码 在底部的Redirect.php中,我包含了可以工作的旧代码 新代码不起作用。我所看到的区别是新的 代码使用$con与数据库通信,我尝试了全局$con和 它也失败了。求你了
还有其他方法,但主要问题是$con在类中不可用。您可以传入构造函数,设置它并在类中使用$this->con:
include("connection.php"); // $con is defined here
$log = new redirect($con); // pass it to __construct()
class redirect
{
public $con;
function __construct($con) // accept it here
{
$this->con = $con; // set it here
}
function get_theme()
{
// use it here
$result = mysqli_query($this->con, "select * from theme where status='yes'");
}
}
您可以使用singleton仅具有一个连接,并且在需要时易于访问:
class connection{
private $con = null;
public static function getCon()
{
if(null === $this->con)
{
$con = mysqli_init( );
if (!$con)
{
die("ERROR: MySQLi Initialed failed");
}
if (!mysqli_real_connect($con, SERVERNAME,USERNAME,PASSWORD,DATABASENAME, NULL, NULL, MYSQL_CLIENT_INTERACTIVE))
{
die("MySQLi Real Connect Error: " . mysqli_connect_error());
}
$this->con = $con;
}
return $this->con;
}
}
当你需要的时候就给它打电话
function get_theme()
{
/********************************************************************/
/* HERE IS THE NEW REDIRECT.PHP CODE BEING TESTED THAT DOESN'T WORK */
/********************************************************************/
$result = mysqli_query(connection::getCon(), "select * from theme where status='yes'")
if(mysqli_num_rows($result)>0)
{
$data=mysqli_fetch_array($result, MYSQLI_ASSOC);
return $data['theme_name'];
}
}
有关信息,您可以在POO模式下使用mysqli。
我建议您这样做,因为您可以轻松地直接返回mysqli对象,而不仅仅是$con重定向::get_主题应该如何访问var$con?这不在他的范围内。这个解决方案的问题是,TPdeveloper需要使用mysqli_query重写对象的每个构造函数和实例你是给我的答案加-1的人吗?不,但我会加-2。你能告诉我为什么吗?只是因为你问:-
function get_theme()
{
/********************************************************************/
/* HERE IS THE NEW REDIRECT.PHP CODE BEING TESTED THAT DOESN'T WORK */
/********************************************************************/
$result = mysqli_query(connection::getCon(), "select * from theme where status='yes'")
if(mysqli_num_rows($result)>0)
{
$data=mysqli_fetch_array($result, MYSQLI_ASSOC);
return $data['theme_name'];
}
}