I am not very experienced in handling databases.
I have an Android Application that is supposed to send queries to and get the subsequent result set from a remote database sever (MySQL).
I have done this by actually sending the query in the form of a JSON to the server. The server script (PHP) then fetches the query and executes it. The result set is then parsed into a JSON again and sent back to the Android app.
My PHP script
function run_query(mysqli $con, $query){ $res=$con->query($query); return $res; } $reply = array(); if(isset($_POST['json'])) { require_once __DIR__.'/config.php'; require_once __DIR__.'/DbController.php'; $json = json_decode($_POST['json'], true); $query = $json['query']; $con = (new DbController())->connect(DBNAME); if(!$con){ $reply['suc']=false; $reply['err_msg']=$con->error; } else{ $res = run_query($con, $query); if(gettype($res)=="boolean"){ $reply['query_reply']=$res; $reply['suc']=true; die(json_encode($reply)); } $i=0; $reply['query_reply']= array(); while($row = $res->fetch_row()){ $reply['query_reply'][$i] = array(); for($j=0;$j<sizeof($row);$j++) $reply['query_reply'][$i][$j]=$row[$j]; $i++; } $reply['suc']=true; } echo json_encode($reply); } As you can see, the 'query' key contains the entire query string that is executed by the MySQL server.
My question is- does this way contain any security (or other) loopholes that I am not aware of? Also, is there a better way to do this?
One of my project-mates suggest that I should chop the query into distinct sections (Like- "query_type" : "SELECT", "table_name" : "LOGIN_TABLE", "where_args": "WHERE x = x", and so on) and send it to the server and thereafter reconstruct the query there and execute.
However, I do not get how this would help. Any suggestions would be greatly appreciated. Thank you in advance.
"As you can see, the 'query' key contains the entire query string that is executed by the MySQL server."- BIG no no. Anyone who knows your endpoint can send lil' Bobby Tables over. Database queries should be handled entirely server-side with appropriate sanitised API endpoints provided to the mobile application.