简体   繁体   English

将Android应用连接到外部数据库(phpmyadmin)

[英]Connect Android app to external Database (phpmyadmin)

I'm trying to connect my android application to an external database. 我正在尝试将我的android应用程序连接到外部数据库。 I have some php scripts on a ftp server that provide some function for my database. 我在ftp服务器上有一些php脚本,它们为我的数据库提供了一些功能。 On my phpmyadmin database i have a table 'users'. 在我的phpmyadmin数据库上,我有一个“用户”表。 when i try to insert a new user my android app access to my php scripts but then the "mysql_query" return always false and the user doesn't appear in my table on the online database. 当我尝试插入新用户时,我的Android应用程序访问我的php脚本,但是“ mysql_query”始终返回false,并且该用户未出现在在线数据库的表中。 in my ftp site i have a index.php file and a folder "include". 在我的ftp站点中,我有一个index.php文件和一个文件夹“ include”。 in this folder i have three files with functions and parameters: config.php, db_connect.php, db_function.php. 在此文件夹中,我具有三个具有功能和参数的文件:config.php,db_connect.php,db_function.php。

probably the error is stupid, but i am new to php. 错误可能是愚蠢的,但我是php新手。 thanks to everyone. 谢谢大家。

here is my java code: i use registerUser to insert the user using getjsonfromurl 这是我的Java代码:我使用registerUser使用getjsonfromurl插入用户

private static String loginURL = "php_script_adress_on_ftp";
    private static String registerURL = "php_script_adress_on_ftp";

    private static String login_tag = "login";
    private static String register_tag = "register";

public JSONObject registerUser(String name, String email, String password){
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", register_tag));
        params.add(new BasicNameValuePair("name", name));
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("password", password));

        // getting JSON Object
        JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
        // return json
        return json;
    }

//that is the jsonfromurl function //这是jsonfromurl函数

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);            
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

here is my index.php file that i call from android app. 这是我从android应用程序调用的index.php文件。 $user = $db->storeUser($name, $email, $password); $ user = $ db-> storeUser($ name,$ email,$ password); return always false with error number '1' error in registration 返回始终为假,错误号为“ 1”的注册错误

<?php

/**
 * File to handle all API requests
 * Accepts GET and POST
 * 
 * Each request will be identified by TAG
 * Response will be JSON data

  /**
 * check for POST request 
 */
if (isset($_POST['tag']) && $_POST['tag'] != '') {
    // get tag
    $tag = $_POST['tag'];

    // include db handler
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();

    // response Array
    $response = array("tag" => $tag, "success" => 0, "error" => 0);

    // check for tag type
    if ($tag == 'login') {
        // Request type is check Login
        $email = $_POST['email'];
        $password = $_POST['password'];

        // check for user
        $user = $db->getUserByEmailAndPassword($email, $password);
        if ($user != false) {
            // user found
            // echo json with success = 1
            $response["success"] = 1;
            $response["uid"] = $user["unique_id"];
            $response["user"]["name"] = $user["name"];
            $response["user"]["email"] = $user["email"];
            $response["user"]["created_at"] = $user["created_at"];
            $response["user"]["updated_at"] = $user["updated_at"];
            echo json_encode($response);
        } else {
            // user not found
            // echo json with error = 1
            $response["error"] = 1;
            $response["error_msg"] = "Incorrect email or password!";
            echo json_encode($response);
        }
    } else
 if ($tag == 'register') {
        // Request type is Register new user
        $name = $_POST['name'];
        $email = $_POST['email'];
        $password = $_POST['password'];

        // check if user is already existed
        if ($db->isUserExisted($email)) {
            // user is already existed - error response
            $response["error"] = 2;
            $response["error_msg"] = "User already existed";
            echo json_encode($response);
        } else {
            // store user
            $user = $db->storeUser($name, $email, $password);
            if ($user) {
                // user stored successfully
                $response["success"] = 1;
                $response["uid"] = $user["unique_id"];
                $response["user"]["name"] = $user["name"];
                $response["user"]["email"] = $user["email"];
                $response["user"]["created_at"] = $user["created_at"];
                $response["user"]["updated_at"] = $user["updated_at"];
                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = 1;
                $response["error_msg"] = "Error occured in Registration";
                echo json_encode($response);
            }
        }
    } else {
        echo "Invalid Request";
    }
} else {
    echo "Access Denied";
}
?>

here is my config.php. 这是我的config.php。 is it correct to specify the host in this way? 以这种方式指定主机是否正确? i also tried with http 我也尝试过http

<?php

/**
 * Database config variables
 */
define("DB_HOST", "sql3.freemysqlhosting.net");
define("DB_USER", "my_user");
define("DB_PASSWORD", "my_psw");
define("DB_DATABASE", "mydb_name");
?>

here is connect_db.php 这是connect_db.php

<?php
class DB_Connect {

    // constructor
    function __construct() {

    }

    // destructor
    function __destruct() {
        // $this->close();
    }

    // Connecting to database
    public function connect() {
        require_once 'include/config.php';
        // connecting to mysql
        $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
        // selecting database
        mysql_select_db(DB_DATABASE);

        // return database handler
        return $con;
    }

    // Closing database connection
    public function close() {
        mysql_close();
    }

}

?>

here is db_functions.php 这是db_functions.php

<?php

class DB_Functions {

    private $db;

    //put your code here
    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // connecting to database
        $this->db = new DB_Connect();
        $this->db->connect();
    }

    // destructor
    function __destruct() {

    }

    /**
     * Storing new user
     * returns user details
     */
    public function storeUser($name, $email, $password) {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt
        $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
        // check for successful store
        if ($result) {
            // get user details 
            $uid = mysql_insert_id(); // last inserted id
            $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
            // return user details
            return mysql_fetch_array($result);
        } else {
            return false;
        }
    }

    /**
     * Get user by email and password
     */
    public function getUserByEmailAndPassword($email, $password) {
        $result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
        // check for result 
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            $result = mysql_fetch_array($result);
            $salt = $result['salt'];
            $encrypted_password = $result['encrypted_password'];
            $hash = $this->checkhashSSHA($salt, $password);
            // check for password equality
            if ($encrypted_password == $hash) {
                // user authentication details are correct
                return $result;
            }
        } else {
            // user not found
            return false;
        }
    }

    /**
     * Check user is existed or not
     */
    public function isUserExisted($email) {
        $result = mysql_query("SELECT email from users WHERE email = '$email'");
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed 
            return true;
        } else {
            // user not existed
            return false;
        }
    }

    /**
     * Encrypting password
     * @param password
     * returns salt and encrypted password
     */
    public function hashSSHA($password) {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }

    /**
     * Decrypting password
     * @param salt, password
     * returns hash string
     */
    public function checkhashSSHA($salt, $password) {

        $hash = base64_encode(sha1($password . $salt, true) . $salt);

        return $hash;
    }



}

?>

EDIT: i modified the db_function.php to return also mysql_error but it return nothing 编辑:我修改了db_function.php还返回mysql_error但它什么也不返回

public function storeUser($name, $email, $password,$error) {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt
        $result = mysqli_query("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
        // check for successful store
        if (!$result) {
            // get user details 
            $uid = mysqli_insert_id(); // last inserted id
            $result = mysqli_query("SELECT * FROM users WHERE uid = $uid");
            // return user details
$error = mysql_error();            
return mysql_fetch_array($result);
        } else {
$error = mysql_error();
            return false;
        }
    }

and i modiied the index.php to return the mysql_error .... .... 我修改了index.php以返回mysql_error .... ...

 $user = $db->storeUser($name, $email, $password,$error);
            if ($user) {
                // user stored successfully
                $response["success"] = 1;
                $response["uid"] = $user["unique_id"];
                $response["user"]["name"] = $user["name"];
                $response["user"]["email"] = $user["email"];
                $response["user"]["created_at"] = $user["created_at"];
                $response["user"]["updated_at"] = $user["updated_at"];
                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = 1;
                $response["error_msg"] = $error;
                echo json_encode($response);
            }

... ... ……

also i used mysqli_query and not mysql_query but nothing changed. 我也使用mysqli_query而不是mysql_query,但没有任何改变。

SOLUTION: I found out that altervista made a redirect of my HTTP POST and after the redirect it became a HTTP GET without parameters. 解决方案:我发现altervista重定向了我的HTTP POST,并且在重定向后它变成了不带参数的HTTP GET。 i don't know what was the reason. 我不知道是什么原因。 i have the domain .com but it redirect the request to .org. 我有域名.com,但它将请求重定向到.org。 so i made the request directly to .org and it starts working! 所以我直接向.org发出了请求,它开始工作了!

SOLUTION: I found out that altervista made a redirect of my HTTP POST and after the redirect it became a HTTP GET without parameters. 解决方案:我发现altervista重定向了我的HTTP POST,并且在重定向后它变成了不带参数的HTTP GET。 i don't know what was the reason. 我不知道是什么原因。 i have the domain .com but it redirect the request to .org. 我有域名.com,但它将请求重定向到.org。 so i made the request directly to .org and it starts working! 所以我直接向.org发出了请求,它开始工作了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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