<?php
include_once('../dbInfo.php');
function getReport($user_table) {
$tables = array(
"day" => "p_day",
"month" => "p_month"
... etc. .....
);
$table = $tables[$user_table];
if(!$table) {
die(json_encode(array("error" => "bad table name")));
}
$con = getConnection(); // getConnection is in '../dbInfo.php'
$query = "select * from " . $table;
$res = mysql_query($query, $con);
if(!$res) {
die(json_encode(array("error" => "no results from table")));
}
$fields_num = mysql_num_fields($res);
$fields = array();
for($i=0; $i < $fields_num; $i++) {
$field = mysql_fetch_field($res);
$fields[$i] = $field->name;
}
$i = 0;
while($row = mysql_fetch_array($res)) {
$rows[$i] = $row;
$i++;
}
$json = array("rows" => $rows, "headers" => $fields);
$jsontext = json_encode($json);
return $jsontext;
}
?>
What this code is doing:
- access the database, selecting rows from a table, and returning them as a serialized json object
- a table name is looked up in
$tables
-- the keys are acceptable user input, the values are actual table/view names in the database - data is selected from the table
- the data is put into a big hash
- the hash is serialized as a json string and returned
Specific issues I'm concerned about:
- security -- is my DB connection info safe? This file is in the root directory of public content, so
dbiInfo.php
, with the database connection information, is not publicly accessible (I think) - security -- am I open to SQL injection attacks? I build a SQL query with string concatenation
- security --
$user_table
is untrusted input; is it safe? It's only used as a key to look up trusted input ... - error handling -- have I dealt with all error conditions
- there are lots of versions of PHP functions -- am I using the right ones?
General issues:
- following conventions
- quality/readability/comments
Edit: the data is publicly available -- I'm worried about somebody getting more than read access to one of the listed tables, or any access to any other table in the DB.