I'm trying to get a function inside of a class to work with another function with no success.
Here is my code:
<?php
class db {
public function dbLogin() {
$mysqli = new mysqli("127.0.0.1","user","passowrd","database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "
";
}
public function selectQuery() {
$this->dbLogin();
$query = "
SELECT column
FROM table
";
if ($mysqli->query($query)) {
echo "success";
}
}
}
$fData = new db();
$fData->dbLogin();
$fData->selectQuery();
?>
The database connection works fine. I cannot get anything to echo once the query line runs, though.
What I've tried so far:
-Replacing the dbLogin()
function with a construct()
function, then getting rid of the $this->dbLogin
line and $fData->dbLogin()
line. This did not work.
-Moving this code around in different variations, just in case my order was wrong. That did nothing.
-Googling/looking at similar questions on StackOverflow with no luck.
I can do this procedural style easily, but it's time for me to move away from that. I am sure that there are much better ways to connect to a database using an OOP design pattern, but I am brand new to OOP so I am trying to use this as a lesson, and to gain a better understanding as to how functions interact with each other inside of a class. I know that I can throw the connection and query in one function, but then I would not know how to make functions interact with one another inside of a class.
How do I run the query in the selectQuery
function based on the login information in the dbLogin
function?