1

is it safely way to use Mysqli_connect link in a function as GLOBALS like on following example ? What problems might I face on with this way ?

function dbconnect(){

$link = mysqli_connect($db['host'], $db['user'], $db['pass']);
mysqli_select_db($link, $db['db']);
return $link;

}

function something_query($sql){

return mysqli_query($GLOBALS['conn'], $sql);

}

$conn = dbconnect();    

$newsql = 'select * from table where 1';
something_query($newsql); 

edit 1 : $conn is an unique string on whole code and it does not use as param in query

chakir
  • 15
  • 4
  • Yes, it is safe if you are following the 'safety rules for injection'. Some related posts can be found http://stackoverflow.com/questions/5840230/how-to-properly-escape-a-string-via-php-and-mysql and http://stackoverflow.com/questions/2688/what-do-i-need-to-escape-when-sending-a-query. – sitilge Apr 11 '15 at 19:22
  • may you explain more clearly, I dont use $conn inside "mysqli_query" how injection could be happen here ? – chakir Apr 11 '15 at 19:37

1 Answers1

0

Yes, it's save (as in, there are no security risks with it).

It is not the best design though. Dependency injection is generally preferred to global variables, as it gives you the opportunity of testing only a small part of your code, and mocking the rest that is not needed for that test, and it increases the reusability of your code (you can just take a class/function and use it in a different project, without reading all the code and checking what values need to exist in global).

tim
  • 1,999
  • 17
  • 32
  • do you have any suggestion to improve security or reusability of this structure ? – chakir Apr 11 '15 at 19:51
  • there's not much to say about security (it's generally not recommended to store credentials in a PHP file inside the web root, but it's not clear where your script is located, so I didn't comment on it in my answer). Storing the connection in `GLOBALS` is fine, and I'm assuming that you use prepared statements for queries. And for reusability, just pass the connection into the function: `something_query($connection, $sql)` – tim Apr 11 '15 at 19:53
  • thank you, that is much usefull then all, however `something_query($connection, $sql) ` is not best solution in my case, if I follow that, I have to change rest of sections which using this one and similar functions – chakir Apr 11 '15 at 21:11