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