我正在构建一个报告工具,用户可以在其中输入一个SQL查询,该工具将返回CSV文件中的结果。除了只写入CSV文件之外,我还需要在这里执行一些附加逻辑。所以 SELECT INTO OUTFILE对我来说就不起作用了。
我知道执行任意用户提供的SQL查询是不好的,但是这个工具只能在内部使用,所以安全性不应该是一个考虑因素。此外,我将其限制为只选择查询。
现在,当我以CSV格式导出数据时,我还希望将查询的列名作为CSV文件中的第一行输出。
因此,我的问题是,是否有一种方法可以在PHP中使用PDO获取SQL查询的列名?MySQL客户端工具(如SequelPro)能够在显示查询结果的同时显示列名。
所以我假设这是可能的,但我找不到方法。
Here I am not writing full PDO connection code. You can use below code/logic to get the return column name.
$stmt = $conn->query("SELECT COUNT(*), first_column, second_column FROM table_name");
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$columns = array_keys($row);
print_r($columns); // array(0 => COUNT(*), 1 => first_column, 2 => second_column)
The keys of the row result are the column names. You can display them like so:
$conn = mysqli_connect(YOUR_CONNECTION_INFO);
$result = mysqli_query($conn, YOUR_QUERY);
$row = mysqli_fetch_assoc($result);
foreach ($row as $key=>$value) {
echo $key;
}
You said security wasn't an issue since the code would only be used internally, but what happens if you create a new database user with limited rights and connect to the database using that user.
That way you can set up the rights as you want from your database and won't have to worry about users dropping tables.