user3638545 user3638545 - 7 months ago 18
SQL Question

query mysql database from inside a class using properties

Hi this is kind of an upgraded version of this question:
query mysql database from inside a class
The difference from the previous question, is i need a dynamic query not a static one or l$query = "SELECT col_1 FROM db.table"; So in order to have a dynamic query i need to use properties (or variables) so i can call different tables from that same class, or something like this "SELECT ‘$data’ FROM ‘$table’ ";

So far my class looks like this, similar to the previous question:

$mysqli = new mysqli("localhost", "root", "", "intranetpugle");

class crudmum {

private $table;
private $data;
private $mysqli;

function __construct($mysqli) {
$this->mysqli = $mysqli;
}


function runQuery($data2, $table2)
{
$this->table = $table2; $this->data = $data2;
$query = "SELECT '$this->data' FROM '$this->table' ";

$stmt = $this->mysqli->prepare($query);
$stmt->execute();
$stmt->bind_result($r);

while($stmt->fetch())
{
echo "<option>" . $r . "</option>";
}
}
};


This is how i run it:

$showme = new crudmum($mysqli);
$showme->runQuery("priority", "trackboards" );


Note: When i dont use variables or properties inside the query or somethng like this, SELECT priority FROM trackboards, the query does work, only when i input the properties or variables (like the given example) it does not work.

I get this error:
Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\devserv\i+d\bootstrap\functions.php on line 76


Anyone see what am i doing wrong, of course there is a mistake with the database query any ideas on how to query the database right in a dynamic way within a class, sorry new with OOP with PHP!

Answer

found the mistake which was to add 'quotes' on the variables, like shown below:

 $query = "SELECT '$this->data' FROM '$this->table' ";

The correct way would be to take out those 'quotes' on the variables or like this:

$query = "SELECT $this->data FROM $this->table ";

With that fix, the query runs just fine, guess i lacked attention to detail, thanx everyone for their help.

Comments