我有连接的配置文件但是当我使用$ this-> con> prepare()或$ this-> con> query()不起作用。 但是,当我为连接创建单独的变量时,下面的工作很好,例如。
此代码无效
private function isEmailexist($email)
{
$stmt = $this->con->prepare("SELECT * FROM devices WHERE email = ?");
$stmt->bind_param("s",$email);
$stmt->execute();
$stmt->store_result();
$rows = $stmt->num_rows;
echo "Rows : ".$rows;
}
此代码工作
private function isEmailexist($email)
{
$mysqli = new mysqli("localhost", "root", "", "demo1");
$stmt = $mysqli->prepare("SELECT * FROM devices WHERE email = ?");
$stmt->bind_param("s",$email);
$stmt->execute();
$stmt->store_result();
$rows = $stmt->num_rows;
echo "Rows : ".$rows;
}
这是配置文件
class Config
{
private $con;
function __construct(){}
function connect()
{
define('DB_USERNAME','root');
define('DB_PASSWORD','');
define('DB_NAME','demo1');
define('DB_HOST','localhost');
$con = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "Connection success...";
return $this->con;
}
}
答案 0 :(得分:1)
您的问题是在$con
connect()
您正在使用
// $con is only visible within the scope of the connect function
$con = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);
但它应该是
// this will set the config class's $con property so that it is re-usable
$this->con = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);