h_a86
h_a86

Reputation: 281

php codeigniter active record class

i have been using codeigniter active record class for database acces, But one thing i want to assure is the database security. My scenario is: I am using this query to access data from database.

$q = $this->db->query("SELECT* FROM mytable WHERE id = '$p'");

After this i use return statement.

return $q->result();

when i load database to my view i encode the array with the json encode function and the json encode function not only shows the value of database table fields but also the table field names. Is it secure or if not how can i avoid displaying table field names thanks.

Upvotes: 0

Views: 581

Answers (3)

allen213
allen213

Reputation: 2277

Do this

$q = $this->db->query("SELECT * FROM mytable WHERE id = ?",array('id'=>$p)); 

Instead for a start

If you are concerned about exposing your field names parse the result and map to something else before returning it (example below more suitable for multiple rows actually).

$ret = array();

foreach($q->result_array() as $row)
{
  $remapped = array();

  $remapped['obscure_name'] = $row['real_name'];
  $ret[]=$remapped;
}

return $ret;

Upvotes: 1

Thomas Fussell
Thomas Fussell

Reputation: 468

You can strip the table field names by changing your return statement to:

return array_values($q->result_array());

Better ways would be to parse the results:

$q = $this->db->query("SELECT* FROM mytable WHERE id = '$p'");
$result = $q->result();

$values[] = $result['id'];
$values[] = $result['column1'];
$values[] = $result['column2'];

return $values;

or specify which columns you need in the SQL statement in case the schema changes:

SELECT id, column1, column2 FROM mytable WHERE id = '$p'

Finally, as allen213 mentioned, you should use bindings to prevent injection attacks:

$sql = 'SELECT * FROM mytable WHERE id = ?';
$q = $this->db->query($sql, array('id' => $p));

Upvotes: 2

Brian Warshaw
Brian Warshaw

Reputation: 22984

I'm not sure how the CI AR class works under the hood, but I can tell you that what you have here seems very insecure because you're passing a value directly into a query instead of using a prepared statement. Basically, if the value of that variable can be manipulated in some way by the requestor, then you can have an SQL injection attack (that's a very bad thing, by the way). That's the security concern I would have if I were you.

Upvotes: 0

Related Questions