PHP连接和查询错误:致命错误:在null中,调用成员函数query()

时间:2019-03-10 23:37:57

标签: php sql mysqli

关于以下语句,我遇到了以上错误,尝试从堆栈中的其他答案进行了多次修复,但继续收到相同的错误:(

这是用户注册表单中php代码的一部分,希望其信息插入表格中

StackOverflowException

我在$ conn的单独文件中有此其他代码

fullname

1 个答案:

答案 0 :(得分:1)

要做的第一件事是创建将返回连接的类:

<?php
//filename: dbConnect.php
class dbConnect
{
	
		public function connect() {
			 global $conn;
				
			 $servername = "localhost";
			 $username  = "root"; 
			 $password = "";
			 $database = "test";  
			// Create connection
			 $conn = new mysqli($servername, $username, $password, $database); 
			// Check connection 
			if  ($conn->connect_error) { 
				die("Connection failed: " . $conn->connect_error); 
			} //echo "Connection successful"; //make variable global to access in other 
			
			return $conn;			
		}
}

?>

现在您可以在另一个文件中执行sql命令:

<?php
require 'dbConnect.php';

	$db = new dbConnect();
	$conn = $db->connect();

	$nome = "Anailton";
	$email = "jose@hotmail.com";
	if($conn->query( "INSERT INTO clientes (NOME, EMAIL) VALUES ('$nome', '$email')")==TRUE){
		echo 'Inserted';
	}else{
		echo 'Not Inserted';
	}

?>