This class is for managing a database through mysqli. I’m stuck on the prepared statement to show all the column names of a given table.
class databaseManager {
function showTable ($tableName, $mysqli) {
$stmt = $mysqli -> prepare("SHOW COLUMNS FROM ?");
$stmt -> bind_param('s', $tableName);
$stmt -> execute();
while ($stmt -> fetch) {
$Field;
}
$stmt -> free_result();
}
}
I get the error “Call to a member function bind_param() on a non-object”, but $mysqli connection exists so I suppose the mysqli -> prepare is wrong.
EDIT: clearly I passed $mysqli
$databaseManager = new databaseManager();
$databaseManager -> showTable("blog", $mysqli);
First, you aren’t doing any error handling.
Always check results of all database interactions.
For example,
so, you will get an error message from database.
Next, you can’t bind identifier via prepared statement.
So, you have to either whitelist it of format it properly, according to documentation
By the way, I see not much point in such a function. I am using console for this purpose and other people usually see their database structure via PHPMyAdmin
Also, using bare API is not the best choice. By using some abstraction layer you can make your code in one line:
You don’t need this query to show table contents though, as column names always already present in a resultset. So, just request your data first and then extract column names from it
by using such a library mentioned above, it would be like this
But still PHPMyAdmin is WAY better at it, give it a try
If you need some sort of online table editor, it is seldom works such straight way. There are always some issues which require pre- or post-processing of data. And for whatever complex data structure you always end up with dedicated code. To show nice column titles for example.
But for a few plain string values it would work.