Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 753
bonini81 Avatar asked Jan 21 '26 12:01

bonini81


1 Answers

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.

like image 155
bonini81 Avatar answered Jan 23 '26 02:01

bonini81



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!