2013-11-04 2 views
0

내 안드로이드 응용 프로그램을 외부 데이터베이스에 연결하려고합니다. 데이터베이스에 대한 일부 기능을 제공하는 ftp 서버에 일부 PHP 스크립트가 있습니다. phpmyadmin 데이터베이스에 'users'테이블이 있습니다. 새 사용자를 내 PHP 스크립트에 대한 내 안드로이드 응용 프로그램 액세스를 삽입하려고 시도하지만 "mysql_query"가 항상 false로 반환되고 사용자가 온라인 데이터베이스의 내 테이블에 나타나지 않습니다. 내 ftp 사이트에서 나는 index.php 파일과 폴더 "include"가 있습니다. 이 폴더에는 config.php, db_connect.php, db_function.php와 같은 함수와 매개 변수가있는 세 개의 파일이 있습니다.안드로이드 애플 리케이션을 외부 데이터베이스 (phpmyadmin)에 연결

아마도 오류는 바보 같지만 PHP는 처음입니다. 모두 덕분에 . 여기

내 자바 코드입니다 : 내가 getjsonfromurl를 사용하여 사용자를 삽입 registerUser를 사용

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; 
    } 

// 즉, 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; 

    } 

내 index.php 파일입니다 그 전 안드로이드 애플 리케이션에서 전화. $ user = $ db-> storeUser ($ name, $ email, $ password); 오류 번호가 '1'인 등록 정보가 항상 false로 반환됩니다.

<?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"; 
} 
?> 

여기는 내 config.php입니다. 이 방법으로 호스트를 지정하는 것이 맞습니까? 나 또한 여기

<?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"); 
?> 

는 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 여기

<?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(); 
    } 

} 

?> 

이 connect_db.php입니다 http로 시도 : 나는 mysql_error를 또한 반환 할 db_function.php을 수정하지만, 반환하지 않음

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; 
     } 
    } 

와 내가 mysql_error를을 .... 돌아가려면의 index.php를 modiied ....

$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); 
      } 

... ...

은 내가 mysqli_query되지는 mysql_query를 사용하지만 아무것도 변경되지 .

는 해결책 : 그 altervista 내 HTTP의 POST의 리디렉션을 만들어 리디렉션 후 매개 변수없이 HTTP GET되었다 발견. 나는 이유가 무엇인지 모른다. 도메인 .com이 있지만 요청을 .org로 리디렉션합니다. 그래서 나는 .org에게 직접 요청을했고 그것은 일하기 시작했다!

+0

'ftp 서버의 PHP 스크립트'나는 FTP 서버가 PHP 파일을 실행할 수 있다고 생각하지 않는다. – Reeno

+0

답변 해 주셔서 감사합니다! 정말 확실합니까? 그리고 어디에 내 PHP 파일을 넣어야합니까? 그리고 ftp 서버가 php 파일을 실행할 수없는 경우 왜 index.php 파일에 "error"문자열을 반환합니까? – user2953054

+0

FTP로 웹 서버에 업로드했다고 생각하십니까? Apache와 같은 웹 서버에서 PHP가 실행됩니다. – Reeno

답변

0

해결 방법 : altervista가 내 HTTP POST를 리디렉션했고 리디렉션 한 후에 매개 변수없이 HTTP GET이 된 것을 알았습니다. 나는 이유가 무엇인지 모른다. 도메인 .com이 있지만 요청을 .org로 리디렉션합니다. 그래서 나는 .org에게 직접 요청을했고 그것은 일하기 시작했다!

관련 문제