0

So I tried to start using mysqli to improve security and this is what I have at the moment: a conectar.php file

<?php
$DBServer = 'X'; // ip o lo que sea
$DBUser   = 'X';
$DBPass   = 'X';
$DBName   = 'X';
 $conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);

 if ($conn->connect_error) {
 trigger_error('Database connection failed: '  . $conn->connect_error, E_USER_ERROR);
  }
   ?>

And then a php file which has the following code:

include("admin/conectar.php");
$categoria = $_GET['categoria'];
if($categoria){
 $query_p = $conn->query("SELECT * FROM `productos` WHERE `categoria` = '$categoria'     ORDER BY nombre ASC");
while($result_p = $query_p->fetch_object()){
$nombre = $result_p->nombre;
$referencia = $result_p->referencia;;
$descripcion = $result_p->descripcion; 
$imagen = $result_p->imagen;

What should I do to prevent hacking or SQL injection?? Should I set up an array so only certain values of $categoria are accepted? Thanks!

Robert Harvey
  • 168,684
  • 43
  • 314
  • 475

1 Answers1

0

Never use such a GET variable as a variable that is used in a SQL query, because someone could change the value of the GET variable into e.g. "DROP TABLE ...". To improve the security of your code:

sinaneker
  • 174
  • 11
  • why did I get a negative vote? – sinaneker Jul 13 '13 at 13:29
  • I was thinking of using an array so that if the GET variable isnt an expected one, it does not do anything... this would prevent any sort of sql injection right? Also, I did read this: http://stackoverflow.com/questions/60174/how-to-prevent-sql-injection-in-php but I dont really understand prepared statements.... btw: I honestly dont know why you got a negative vote, it seems like a perfect answer to me – Daniel Antón García Jul 13 '13 at 13:48
  • @DanielAntónGarcía ah ok! When you want I can teach you what prepared statements are ;) Also I wrote this answer before the comment appears or I didn't noticed it. – sinaneker Jul 13 '13 at 14:12
  • Could you help me with it? http://stackoverflow.com/questions/17633573/login-using-php-and-mysqli Thanks a lot! – Daniel Antón García Jul 14 '13 at 07:33