嘿伙计们我是OOP的新手,我想要运行两个需要相同连接的功能。我正在努力以一种允许两个函数使用它的方式声明$ mysqli变量。我宁愿只使用一个,因为我稍后会添加更多功能。非常感谢任何帮助。
我收到的错误信息是;
注意:未定义的变量:第13行的C:\ Users \ PC \ Documents \ XAMPP \ htdocs \ test.php中的mysqli
<?php
class OOP
{
function __construct(){
$mysqli = new mysqli('localhost', 'c3337015', 'c3337015', 'iitb');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
function getMember(){
$stmt = $mysqli->prepare("SELECT First_Name FROM forum members");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($First_Name);
while ($row = $stmt->fetch()) {
echo $First_Name;
}
}
function getForum(){
$stmt = $mysqli->prepare("SELECT ForumTitle FROM forum");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($ForumTitle);
while ($row = $stmt->fetch()) {
echo $ForumTitle;
}
}
}
答案 0 :(得分:2)
您在构造函数中声明$mysqli
,但它不是类变量。您只需将其添加为类变量:
class OOP {
private $mysqli;
...
然后,只要您想要访问该变量,请将$mysqli
替换为$this->mysqli
。
答案 1 :(得分:0)
<?php
/**
* My file
* @author yourname
*
*/
class OOP {
/** ============ class vars ============ **/
/**
* DocBloc comment
* @var mysqli
*/
private $mysqli = null;
/** ============ class methods ============ **/
function __construct()
{
$this->mysqli = new mysqli ( 'localhost', 'c3337015', 'c3337015', 'iitb' );
if (mysqli_connect_errno ()) {
printf ( "Connect failed: %s\n", mysqli_connect_error () );
exit ();
}
}
/*
* DocBloc
*/
function getMember()
{
$stmt = $this->mysqli->prepare ( "SELECT First_Name FROM forum members" );
$stmt->execute ();
$stmt->store_result ();
$stmt->bind_result ( $First_Name );
while ( $row = $stmt->fetch () ) {
echo $First_Name;
}
}
/*
* DocBloc
*/
function getForum()
{
$stmt = $this->mysqli->prepare ( "SELECT ForumTitle FROM forum" );
$stmt->execute ();
$stmt->store_result ();
$stmt->bind_result ( $ForumTitle );
while ( $row = $stmt->fetch () ) {
echo $ForumTitle;
}
}
}