Rozaimi Rozaimi - 1 month ago 9
PHP Question

How to use $this in mysqli connection ?

i declare mysqli connections in connections.php . i declare $this->connection instead of $connect since i want to separate each functions in one file.

<?php
$this->connection = mysqli_connect("localhost","root","","itdforum");

if(mysqli_connect_errno){
echo "Failed to connect to MYSQL: " . mysqli_connect_error();
}
?>


i'm trying to use the $this-connection in other functions

<?php
include("connections.php");
function getSome(){

$get_some = "SELECT * FROM table"
$run_some = mysqli_query($this->connection, $get_some);
}
?>


but error show as below

Using $this when not in object context in localhost\connections.php


anyone knows how to fix it ? or i just add all the functions into one php file only ? thanks.

Answer

It sounds like you want a class:

class Thing {
    function __construct(){
        $this->connection = mysqli_connect(...)
        if(mysqli_connect_errno){
            echo "Failed to connect to MYSQL: " . mysqli_connect_error();
        }
    }

    function getSome(){
        $get_some = "SELECT * FROM table"
        $run_some = mysqli_query($this->connection, $some);
    }

}

To use it:

include('Thing.php');

$thing = new Thing();

$thing->getSome();