This question already has an answer here:
I want to have something like this stored in a php file:
class SQL
{
public db_host = "localhost";
public db_username = "user";
public db_password = "pass";
public db_databaseName = "myDatabase";
public function sql_connect()
{
$connectDb = new mysqli("$this->db_host", "$this->db_username", "$this->db_password", "$this->db_databaseName");
if($connectDb->connect_error) {
exit("Error connecting to database");
} else {
echo "Successfully connected to the database";
}
}
public function sql_command()
{
// Call the sql connect method:
$this->sql_connect();
<< my code to send sql and contains the $connectDb var from the sql_connect() method >>
}
}
I wanted to keep the code used to connect to the database in a separate method so that it can be re-used with multiple methods that contain different sql commands and will all need to connect to the database in order to run.
However, when I run the code the sql_connect method runs but the $connectDb var is not available to the sql_command method and I need it to be.
I have tried various different ways of getting this to work, to no avail.
Any help that can be offered would be appreciated :)
</div>