简体   繁体   中英

Not able to insert record to MySQL, but showing no error

Task: sync records from android sqlite to mysql.

Problem: mysql/php is not inserting data into my table in mysql. But no errors were shown.

DB_Connect.php:

<?php

class DB_Connect {

    // constructor
    function __construct(){

    }

    // destructor
    function __destruct(){

    }

    // connecting to database
    public function connect(){
        require_once 'config.php';  // defined DB_HOST,DB_USER,DB_PASSWORD here
        // connecting to mysql
        $con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);
        // selecting database
        mysqli_select_db($con,"heart");
        // return database handler
        return $con;
    }

    // closing database connection
    public function close(){
        mysqli_close($this->connect());
    }
}

?>

DB_Operations.php:

<?php
class DB_Operations {

    private $db;
    public $last_id;
    public $error;
    public $error_conn;
    public $error_no;

    // constructor
    function __construct(){
        require 'DB_Connect.php';
        $this->db = new DB_Connect();
        $this->db->connect();
    }

    // destructor
    function __destruct(){

    }

    // Storing new doctor
    public function storeDoctor($_id,$firstName,$lastName,$specialization,$licenseNumber,$clinicAddress,$email,$contactNum,$username,$password,$aboutMe){
        $result = mysqli_query($this->db->connect(),"INSERT INTO doctor(_id,first_name,last_name,specialization,license_number,clinic_address,email,contact_number,username,password,about_me) VALUES('$_id','$firstName','$lastName','$specialization','$licenseNumber','$clinicAddress','$email','$contactNum','$username','$password','$aboutMe')");

        if (mysqli_connect_errno()){
            $this->error_conn = mysqli_connect_error();
        }

        if(!$result){
            if(mysqli_errno($this->db->connect()) == 1062){
                // duplicate key - primary key violation
                return true;
            } else{
                // for other reasons
                $this->error = mysqli_error($this->db->connect());
                $this->error_no = mysqli_errno($this->db->connect());
                return false;
            }
        } else{
            $this->last_id = mysqli_insert_id($this->db->connect());
            return true;
        }
    }

    // getters
    public function getError(){
        return $this->error;
    }
    public function getError_no(){
        return $this->error_no;
    }
    public function getError_conn(){
        return $this->error_conn;
    }
    ...

insertuser.php:

<?php
include 'DB_Operations.php';
// create object for DB_Operations class
$db = new DB_Operations();
// get JSON posted by Android Application
$json = $_POST["doctorsJSON"];
// remove slashes
if(get_magic_quotes_gpc()){
    $json = stripslashes($json);
}
// decode JSON into Array
$data = json_decode($json);
// util arrays to create response JSON
$a = array();
$b = array();
// loop through an array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data); $i++){
    // store doctor into MySQL DB
    $res = $db->storeDoctor($data[$i]->_id,$data[$i]->first_name,$data[$i]->last_name,$data[$i]->specialization,$data[$i]->license_number,$data[$i]->clinic_address,$data[$i]->email,$data[$i]->contact_number,$data[$i]->username,$data[$i]->password,$data[$i]->about_me);

    // based on insertion, create JSON response
    $b["local_id"] = $data[$i]->_id;
    if($res){
        $b["server_id"] = $db->last_id;
        $b["status"] = 'yes';
    }else{
        $b["status"] = 'no';
        $b["err_no"] = $db->getError_no();
        $b["error"] = $db->getError();
        $b["error_conn"] = $db->getError_conn();
    }
    array_push($a,$b);
}

// post JSON response back to Android Application
echo json_encode($a);
?>

I have a function in java which syncs the sqlite data to mysql:

public void syncSQLiteToMySQL(Context context,String selectQuery){
    dop = new DatabaseOperations(context);
    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams params = new RequestParams();
    ArrayList<HashMap<String,String>> doctorList = new ArrayList<HashMap<String,String>>();
    doctorList = dop.getAllDoctors();
    if(doctorList.size()!=0){
        String json = dop.composeJSONfromSQLite(selectQuery);
        params.put("doctorsJSON", json);
        Log.i("json to pass", json);
        client.post("http://"+ip+":8080/changed_server_name/insertuser.php",params ,new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                Log.e("client response",response);
                try {
                    JSONArray arr = new JSONArray(response);
                    for(int i=0; i<arr.length();i++){
                        JSONObject obj = (JSONObject)arr.get(i);
                        // did something with json response here
                        dop.updateSyncStatus(obj.getString("local_id"),obj.getString("status"));
                    }
                    message = "DB Sync completed!";
                } catch (JSONException e) {
                    message = "Error Occured [Server's JSON response might be invalid]!";
                    Log.e("JSONException",e.getMessage());
                }
            }

            @Override
            public void onFailure(int statusCode, Throwable error, String content) {
                if(statusCode == 404){
                    message = "Requested resource not found";
                }else if(statusCode == 500){
                    message = "Something went wrong at server end";
                }else{
                    message = "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]";
                    Log.e("sync post failure",error.toString());
                }
            }
        });
    }
}

So, here's the response:

[{"local_id":"0","status":"no","err_no":0,"error":"","error_conn":null}]

The JSON works fine. No problem with it. I have checked and it passes correct data. Just the PHP and MySQL side. Somehow, I couldn't find the error to this code. There is no error message, error number is 0, and there was no error in connecting to DB. But the query in storeDoctor() returns false. How could this be? I have been reading about this problem on this site and others, but I have not really found something that's close to my problem.

Please enlighten me. Your help would really be appreciated. Thanks in advance.

Edit: I also tried mysqli_ping($this->db->connect()); and it returns true which means the connection is okay. So, what really is this something that makes the query fail?

Did you try using error_reporting(E_ALL);

Also inside the constructor you used $this->db->connect();

And then in the store you used $result = mysqli_query($this->db->connect(),

Can you post the code for connect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM