简体   繁体   中英

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.

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, $get_some);
    }

}

To use it:

include('Thing.php');

$thing = new Thing();

$thing->getSome();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM