0

i have an android application that should insert an entry in a table, however to achieve that two inserts should be done first in the tables that have the foreign keys of the corresponding table. if i insert the entries manually on the phpmyadmin (each table by itself) everything works just fine, so the error must be in the php script below:

   <?php



$response = array();

     // check for required fields
      if (isset($_POST['UserName']) && isset($_POST['Password']) && isset($_POST['BankName']) && isset($_POST['TransId']) && isset($_POST['Name'])
 && isset($_POST['City']) && isset($_POST['Region']) && isset($_POST['Gender']) && isset($_POST['Email']) && isset($_POST['Phone'])
           ) {

$UserName = $_POST['UserName'];
$Password = $_POST['Password'];
$BankName = $_POST['BankName'];
$TransId = $_POST['TransId'];
$Name = $_POST['Name'];
$City = $_POST['City'];
$Region = $_POST['Region'];
$Gender = $_POST['Gender'];
$Email = $_POST['Email'];
$Phone = $_POST['Phone'];

$query1 = "INSERT INTO location(`GeoPosition`, `City`, `Region`) VALUES (NULL,'$City','$Region')";
$result1 = mysql_query($query1);
if ($result1) {

    $query2 = "Insert into bank(BankName, BankId , TransId , moneyReceived , CreditCardId ,CustomerName)
                Values ('$BankName',NULL,'$TransId',1,NULL,'$Name')";
    $result2 = mysql_query($query2);
    if($result2){

        // mysql inserting a new row
        $query3= "INSERT INTO premiumseeker(UserName, Password, BankName,TransId, uploadCV ,Name, CreditCardId, Email,City,Region,Gender,Phone)
                            VALUES('$UserName', '$Password', '$BankName','$TransId', NULL,'$Name',NULL,'$Email', '$City', '$Region','$Gender','$Phone')";
        $result3 = mysql_query($query3);                            

        // check if row inserted or not
        if($result3){

            // successfully inserted into database
            $response["success"] = 1;
            $response["message"] = "Premium Seeker successfully registered.";

            // echoing JSON response
            echo json_encode($response);
        }else{
                $response["success"] = 0;
                $response["message"] = "Failed to register Seeker";
        }   
    }else{
                $response["success"] = 0;
                $response["message"] = "Failed to insert bank entry";
    }       
}else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.".$City;

    // echoing JSON response
    echo json_encode($response);
}
      } else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
  }
      ?>

so the json response is oops an error occured ... none of the inserts is being done

The Error is : Value of type java.lang.String cannot be converted to JSONObject

here's the Java code:

     int success;
        String Name = etPremiumSeeker.getText().toString();
        String City = etPseekerCity.getText().toString();
        String Region = spinnerRegion.getSelectedItem().toString();
        String BankName = etBankPSeeker .getText().toString();
        String Email = etPSeekerMail.getText().toString();
        String Phone = etPSeekerPhone.getText().toString();
        String UserName = etPSeekerUser.getText().toString();
        String Password = etPSeekerPass.getText().toString();
        String TransId = "1245";

        try {

           /* try {
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                md5.update(password.getBytes(),0,password.length());
                password = new BigInteger(1,md5.digest()).toString(16);
                //System.out.println("Signature: "+signature);

            } catch (final NoSuchAlgorithmException e) {
                e.printStackTrace();
            }*/

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("UserName", UserName));
            params.add(new BasicNameValuePair("Password", Password));
            params.add(new BasicNameValuePair("BankName", BankName));
            params.add(new BasicNameValuePair("TransId", TransId));
            params.add(new BasicNameValuePair("Name", Name));
            params.add(new BasicNameValuePair("City", City));
            params.add(new BasicNameValuePair("Region", Region));
            params.add(new BasicNameValuePair("Gender", Gender));
            params.add(new BasicNameValuePair("Email", Email));
            params.add(new BasicNameValuePair("Phone", Phone));


            // Log.d("request!", "starting");

            //Posting user data to script
            JSONObject json2 = jsonParser2.makeHttpRequest(
                    REGISTER_URL, "POST", params);

            // full json response
             Log.d("Register attempt", json2.toString());

            // json success element
            success = json2.getInt(TAG_SUCCESS);
            if (success == 1) {
                    Log.d("User Created!", json2.toString());
                //finish();
                return json2.getString(TAG_MESSAGE);
            } else {
                    Log.d("Registration Failure!", json2.getString(TAG_MESSAGE));
                    return json2.getString(TAG_MESSAGE);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }
  • 2
    [Your script is at risk for SQL Injection.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Please, [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and consider using [PDO](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard May 06 '15 at 19:01
  • Add error checking, such as `or die(mysql_error())` to your queries. Or you'll find the issues in your current error logs. – Jay Blanchard May 06 '15 at 19:01
  • Never ever output a fixed (useless) "error" message, especially when you know it's not working, and the system can TELL you what the problem is. `if (!$result) { die(mysql_error()); }` – Marc B May 06 '15 at 19:03
  • Add error reporting to the top of your file(s) right after your opening PHP tag for example ` – Funk Forty Niner May 06 '15 at 19:05
  • and what is the "error" you are getting? – raidenace May 06 '15 at 19:07
  • i should write die(json_encode(mysql_error())); so that the error is sent to application? – Ibrahim Karaki May 06 '15 at 19:08
  • `$result1 = mysql_query($query1) or die(mysql_error());` and do the same for the other queries and what I said earlier about error reporting. – Funk Forty Niner May 06 '15 at 19:09
  • okay i did or die(mysql_error()), by this the error will be sent to log of the android app? if not how to send it? json_encode(mysql_error()) ?? – Ibrahim Karaki May 06 '15 at 19:12
  • no that should have been sent to your screen – Funk Forty Niner May 06 '15 at 19:23
  • the error is value of type java.lang.String cannot be converted to JSONObject – Ibrahim Karaki May 06 '15 at 21:48

1 Answers1

0

You should connect to the server first:

http://php.net/manual/en/function.mysql-connect.php

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_selected = mysql_select_db('foo', $link);

$query1 = "INSERT INTO location(`GeoPosition`, `City`, `Region`) VALUES (NULL,'$City','$Region')";
$result1 = mysql_query($query1);
if ($result1) {
Alex
  • 16,739
  • 1
  • 28
  • 51