mysql - Can't connect to database by calling function in class using PHP

Solution:

You want to use the class variable $conn everywhere (this will be written as $this->conn) instead of $conn (which is a local variable).

Replacing all occurences of $conn by $this->conn in your code will solve that problem.

Answer

Solution:

The main reason it was not working is you are using $this->conn->connect_error in connect function while storing connection in $conn which is local variable and not class variable
If you dont want to call $this->connect(); in every function then below code might work for you

class save extends forma
{
    private $servername = 'localhost';
    private $username = 'root';
    private $password = '';
    private $dbname = 'world';

    public $conn;

    protected $table = 'test_table';

    public function __construct()
    {
        if (!$this->table)
            die('No table name provided');
        $this->connect();
    }


    function connect()
    {

        $this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);

        if ($this->conn->connect_error) {
             
            die($this->conn->connect_error);
        }
        return $this->conn;
    }

    public function saugoti($id,$pakeitimui=0, $kas=0)
    {
        if(isset($_POST['saugoti']))
        {
            $table = "bmp_test";

            $id = $_POST['id'];
            $pav = $_POST['pav'];
            $adr = $_POST['adr'];
            $tel = $_POST['tel'];

            if ($pakeitimui == 0)
            {
                $sql1 = "SHOW FIELDS FROM $table ";
                $result = $this->conn->query($sql1);

Source