P粉6747571142023-09-05 11:18:10
If your users are to provide SQL statements to be used, they must know the names of the tables and columns they want.
You can query the information_schema.COLUMNS
table to find table and column names and data types.
Alternatively, after executing the query, you can obtain the column metadata. For PDO, use $stmt->getColumMeta($columnNumber);. Using mysqli use ->result_metadata() like this (not debugged).
$stmt = $mysqli->prepare("SELECT what,ever,else FROM table"); $stmt->execute(); $metadata = $stmt->result_metadata(); $column_count = $mysqli->field_count(); $column_names = []; for ($colnum = 0; $colnum < $column_count; $colnum++) { $field = $metadata->fetch_field(); $column_names [] = $field->name; } $metadata->close();
This uses ->fetch_field() to get a lot of useful information about each column in the result set.
But asking users to provide you with SQL statements is a big security risk. If you trust users to provide you with SQL statements, you must also trust them not to corrupt or corrupt your data. If your system is open to the global internet, you will lose data. Sometimes people ask me how I know this.