I'm trying to run a query to a MySQL database from within a class and it's not working for some reason. I have the class in a separate file which I'm linking to with the require_once()
function.
here's what the main .php file looks like:
<?php
require_once("connect.php");
require_once("theClass.php");
$a = new theClass;
$a->runQuery();
}
connect.php:
<?php
//connect to mySQL database
$mysqli = new mysqli("host", "user", "password", "db");
if ($mysqli->connect_errno)
{
echo "<br><h1>Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error . "</h1><br>";
}
theClass.php:
<?php
require_once('connect.php');
class theClass
{
//class variables and other functions here
function runQuery()
{
$query = "SELECT col_1 FROM db.table";
$stmt = $mysqli->prepare($query);
stmt->execute();
$stmt->bind_result($r);
while($stmt->fetch())
{
echo $r . "<br>";
}
}
};
I've tried copying the class into the main .php file and it still doesn't work; however, I have used the exact same code( the query, prepare, execute, bind_result, and fetch part) in an external .php file as well as inside the main .php file and it has worked both times. This leads me to believe that you're not able to run queries from inside a class or that there is a different way of going about doing so. Could anyone point me in the right direction?
Thanks
Pass it to the method itself
You have to pass the database object to the method, because they are not in the same scope:
and call it like
Pass it to the constructor
If your class makes a lot of database calls, you could simply pass it in the constructor and save it as a private variable for later use:
and call it like
Both methods make it clear that the dependency of your class is a mysqli object, which is good for future maintenance and readability.
You need to either pass $mysqli as a parameter or use global $mysqli