rok259 Posted May 2, 2014 Share Posted May 2, 2014 (edited) Hello all, Can someone assist me? My knowledge of PHP is slim and I have been learning most of it using W3school over the last couple of weeks. I require my script to use POST and GET to received and send JSON encoded data from my database to my mobile app. I have created the script and have managed to POST, but I can’t get it to return the information I need with GET. Basically user enters Username & Password -> JSON -> PHP decodes and checks both match and sends back database unique ID for that user. I can’t be sure if it is my PHP or JSON that’s causing my issue. <?php $port = '3306'; $link = mysql_connect('localhost', 'username', 'password'); // database connection strings. change these to your DB and Table names. $dbName = "project"; $tableName = "User"; if (!$link) { exit('Error: Could not connect to MySQL server!'); } // connect to the table mysql_select_db($dbName)or die("cannot select DB"); // lets prepare some files to capture what is going on. $incomingJson = 'json.txt'; $fullArray = 'fullArray.txt'; // needed if you enable the debugging secton below $sqlErrorLog = "sqlErrors.txt"; // initialize the string with a blank value $string = ""; // start SEND data if ($_SERVER['REQUEST_METHOD'] === 'POST') { //capture incoming data error_reporting(E_ALL | E_STRICT); $sig = $_POST["sig"]; $jsondata = $_POST["params"]; // this line captures the sent data so you can figure out what you need to send back. file_put_contents($incomingJson,$jsondata); // this line tells the application that the data send was successful. echo '{"Status":"Success"}'; // convert JSON to an array $array = json_decode($jsondata, TRUE); /* // formats the array to view it easier $results = print_r($array,true); file_put_contents($fullArray,$results); */ //get the total number of objects in the array $arrlength = count($array['Children']['1']['Properties']); // set while loop index $i = 0; //loop through array node and get row values while ($i < $arrlength ) { // get row value $value = $array['Children']['1']['Properties'][$i]['Value']."n"; // convert delimited string to an array $arrayPieces = explode("|", $value); // get array values. This section would have to be modified to capture each value you are interested in. $rowName = $arrayPieces[0]; // this variable will be blank if you don't name your rows. $Username = $arrayPieces[2]; $Password =$arrayPieces[3]; // construct SQL statement $sql="INSERT INTO ".$tableName."(username, password)VALUES('$Username', '$Password')"; // insert SQL statement $result=mysql_query($sql); // catch any errors if($result){ // if successful do nothing for now. } else { // if failure, write to custom log $sqlError = "Error writing to databasen"; file_put_contents($sqlErrorLog, $sqlError, FILE_APPEND); } $i++; } } // end of POST if ($_SERVER['REQUEST_METHOD'] === 'GET') { $username = $_GET["username"]; $pass = $_GET["password"]; $query = 'SELECT * FROM User WHERE username="' . mysql_real_escape_string($username) . '" or email="' . mysql_real_escape_string($email) . '"'; $dbresult = mysql_query($query, $link); if (!$dbresult) { //echo "query failed"; $result = array(); $result["result"] = 403; $result["message"] = mysql_error(); echo json_encode($result); mysql_free_result($dbresult); exit; } $player = mysql_fetch_array($dbresult, MYSQL_ASSOC); if (strcmp($player["password"],md5($password)) == 0) { $result = array(); $result["result"] = 200; $result["message"] = "Success"; $result["id"] = $player["id"]; $query = sprintf("UPDATE players SET lastlogin=NOW() WHERE id=%s;", $player["id"]); $uresult = mysql_query($query, $link); if ($uresult) { //code if your update failed. Doesn't really impact what we are doing. so do nothing. } echo json_encode($result); } else { //echo "password mismatch"; $result = array(); $result["result"] = 403; $result["message"] = "Forbidden"; echo json_encode($result); }} else { $result = array(); $result["result"] = 400; $result["message"] = "Bad Request"; echo json_encode($result);}error_reporting(E_ALL | E_STRICT);exit;?> Edited May 3, 2014 by rok259 Link to comment Share on other sites More sharing options...
justsomeguy Posted May 2, 2014 Share Posted May 2, 2014 That's a lot of code. What actually happens when you run it, what is the actual problem?Note that setting the error reporting level to 1 will only show fatal runtime errors, nothing else. You can use E_ALL to show all errors.http://www.php.net/manual/en/errorfunc.constants.php Link to comment Share on other sites More sharing options...
rok259 Posted May 3, 2014 Author Share Posted May 3, 2014 (edited) That's a lot of code. What actually happens when you run it, what is the actual problem?Note that setting the error reporting level to 1 will only show fatal runtime errors, nothing else. You can use E_ALL to show all errors.http://www.php.net/manual/en/errorfunc.constants.php Thanks I have managed to get the script to run it shows; {"result":403,"message":"Forbidden"} But when I try GET it still doesn't send back the id from the username == password. The issue is from line 177. Also I know the information on GET works to a point as it triggers a callback, but I can't be sure if it sends back the JSON data correctly. Edited May 3, 2014 by rok259 Link to comment Share on other sites More sharing options...
rok259 Posted May 3, 2014 Author Share Posted May 3, 2014 Hi, Just wanted to update what I have changed if anyone can help. I am still able to POST to the database, but cant select the information from the database and return what I need. I have added some JSON. Not sure if it would be better to use json_encode() <?php $port = '3306'; $link = mysql_connect('localhost', 'username', 'password'); // database connection strings. change these to your DB and Table names. $dbName = "project"; $tableName = "User"; if (!$link) { exit('Error: Could not connect to MySQL server!'); } // connect to the table mysql_select_db($dbName)or die("cannot select DB"); // lets prepare some files to capture what is going on. $incomingJson = 'json.txt'; //$fullArray = 'fullArray.txt'; // needed if you enable the debugging section below $sqlErrorLog = "sqlErrors.txt"; // initialize the string with a blank value $string = ""; // start SEND data if ($_SERVER['REQUEST_METHOD'] === 'POST') { //capture incoming data error_reporting(E_ALL | E_STRICT); $sig = $_POST["sig"]; $jsondata = $_POST["params"]; // this line captures the sent data so you can figure out what you need to send back. file_put_contents($incomingJson,$jsondata); // this line tells the application that the data send was successful. echo '{"Status":"Success"}'; // convert JSON to an array $array = json_decode($jsondata, TRUE); /* // formats the array to view it easier $results = print_r($array,true); file_put_contents($fullArray,$results); */ //get the total number of objects in the array $arrlength = count($array['Children']['1']['Properties']); // set while loop index $i = 0; //loop through array node and get row values while ($i < $arrlength ) { // get row value $value = $array['Children']['1']['Properties'][$i]['Value']."n"; // convert delimited string to an array $arrayPieces = explode("|", $value); // get array values. This section would have to be modified to capture each value you are interested in. $rowName = $arrayPieces[0]; // this variable will be blank if you don't name your rows. $username = $arrayPieces[2]; $password =$arrayPieces[3]; $email = $arrayPieces[4]; // construct SQL statement $sql="INSERT INTO ".$tableName."(username, password, email)VALUES('$username', '$password', '$email')"; // insert SQL statement $result=mysql_query($sql); // catch any errors if($result){ // if successful do nothing for now. } else { // if failure, write to custom log $sqlError = "Error writing to databasen"; file_put_contents($sqlErrorLog, $sqlError, FILE_APPEND); } $i++; } } // end of POST // start GET data if ($_SERVER['REQUEST_METHOD'] === 'GET') { error_reporting(E_ALL | E_STRICT); $username = $_GET["username"]; $password = $_GET["password"]; // initialize the JSON body variable $jsonBody=""; // get table contents //$query = mysql_query("SELECT * FROM ".$tableName); $query = mysql_query("SELECT * FROM User WHERE ". $username ." = '$password or your text/value'"); // construct an array to hold the data we pull from mySQL $rows = array(); // loop through the table and drop the data into the array while($row = mysql_fetch_assoc($query)) { $rows[] = $row; } // get the number of rows in the array. We need this in the JSON return $arrlength = count($rows); // set while loop index $i = 0; //loop through array node and get row values while ($i < $arrlength ) { // tables we are capturing $id = $rows[$i]['id']; $username = $rows[$i]['username']; $password =$rows[$i]['password']; $email = $rows[$i]['email']; // table row numbers. our index starts at 0, so we want to increment it by 1 to get valid row numbers. $tableRow = $i+1; // construct the JSON return from our data $jsonString = '{"Name":"'.$tableRow .'","Value":"|'.$id.'|'.$username.'|'.$password.'|'.$email.'|"},'; //$jsonString = '{"Name":"'.$tableRow .'","Value":"|'.$id.'|"},'; // append the JSON return with the new data $jsonBody=$jsonBody.$jsonString; // increase index and loop again if not at end of array. $i++; } // construct the JSON response // this is the header of the JSON return. It will have to be adjusted to match whatever your app is expecting. We have to define this here to get the row count above. $jsonHeadher='{"Properties":[],"Name":"","Children":[{"Properties":[{"Name":"rowCount","Value":'.$arrlength.'}, {"Name":"columnCount","Value":4},{"Name":"0-1-name","Value":"id"}, {"Name":"0-1-type","Value":2},{"Name":"0-2-name","Value":"username"}, {"Name":"0-2-type","Value":1},{"Name":"0-3-name","Value":"password"}, {"Name":"0-3-type","Value":1},{"Name":"0-4-name","Value":"email"}, {"Name":"0-4-type","Value":1}],"Name":"id934412_headers","Children":[]}, {"Properties":['; // this is the footer of the JSON return. Again it will have to be adjusted to match whatever your app is expecting. $jsonFooter='],"Name":"id934412","Children":[]}]}'; // removes an extra comma that the loop above leaves behind $jsonBody=rtrim($jsonBody, ","); // constructing the full JSON return $returnedJson=$jsonHeadher.$jsonBody.$jsonFooter; // write the JSON data so the app can read it. echo $returnedJson; } // end of get // close the SQL connection mysql_close($link);?> Link to comment Share on other sites More sharing options...
davej Posted May 4, 2014 Share Posted May 4, 2014 Why would you want to use GET for a login? Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now