Skip to content
Advertisement

Looking for help to make a select statement dynamic

I want to make a dynamic select statement that can select whatever table I ask for, same with table columns in my database.

Here is my select class so far:

Here is my database class

What I’m doing so far is connecting to my Database with mysqli then I extend my select class from my database class so I can get the connection and then I want to select all from.

Advertisement

Answer

First of all, your select class is extending the database class, so there’s no point re-declaring public $result = array(); in select class, it’s not even necessary actually.

Second, since you’re not using object properties outside of the class, make them private.

And finally, since you’re dealing with variable number of arguments, make use of func_get_args() function.

Here’s the reference:

Well based on your requirement, the solution would be to send variable number of arguments to selectQuery() method and use func_get_args() to get an array comprising a function’s argument list.

  • The first argument is the table name and rest of the arguments are column names(if provided)
  • If only one argument is passed to the function then the SELECT query would be SELECT * FROM table_name
  • And if more than one argument is passed to the function then the SELECT query would be SELECT column1, column2, column3, ... FROM table_name

So your code should be like this:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement