使用php mysql连接简单注册应用程序

时间:2015-05-15 16:32:51

标签: php android mysql

我正在尝试按照此处的教程http://www.mybringback.com/android-sdk/13193/android-mysql-php-json-part-5-developing-the-android-application/创建一个简单的客户端 - 服务器登录并注册应用程序。 但显然我卡在注册步骤,我无法注册新帐户,这里是logcat:

05-15 23:16:35.201: D/Login attempt(24225): {"message":"Database Error2. Please Try Again!","success":0}
05-15 23:16:35.201: D/Login Failure!(24225): Database Error2. Please Try Again!

我不确定问题是什么,我希望有人能帮助我,我真的很感激。

首先来到wampserver中的数据库和表格:

create database smkkimmanuel2

use smkkimmanuel2

create table users(
   uid int(11) primary key auto_increment,
   username varchar(20) not null unique,
   password varchar(20) not null,
   level_akses varchar (1) not null,
   jabatan varchar (30) not null);

和我从教程创建的php文件:

的config.php

<?php

    $username = "root";
    $password = "";
    $host = "localhost";
    $dbname = "smkkimmanuel2";

    $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); 

    try 
    { 
        $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); 
    } 
    catch(PDOException $ex) 
    { 
        die("Failed to connect to the database: " . $ex->getMessage()); 
    } 

    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);      
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 

    if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) 
    { 
        function undo_magic_quotes_gpc(&$array) 
        { 
            foreach($array as &$value) 
            { 
                if(is_array($value)) 
                { 
                    undo_magic_quotes_gpc($value); 
                } 
                else 
                { 
                    $value = stripslashes($value); 
                } 
            } 
        } 

        undo_magic_quotes_gpc($_POST); 
        undo_magic_quotes_gpc($_GET); 
        undo_magic_quotes_gpc($_COOKIE); 
    } 

    header('Content-Type: text/html; charset=utf-8'); 

    session_start(); 

?>

这是我的register.php:

<?php

require("config.php");

if (!empty($_POST)) {
    if (empty($_POST['username']) || empty($_POST['password'])) {

        $response["success"] = 0;
        $response["message"] = "Please Enter Both a Username and Password.";

        die(json_encode($response));
    }

    $query        = " SELECT 1 FROM user_id WHERE username = :user";
    $query_params = array(
        ':user' => $_POST['username']
    );

    try {
        $stmt   = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch (PDOException $ex) {
        $response["success"] = 0;
        $response["message"] = "Database Error1. Please Try Again!";
        die(json_encode($response));
    }

    $row = $stmt->fetch();
    if ($row) {

        $response["success"] = 0;
        $response["message"] = "I'm sorry, this username is already in use";
        die(json_encode($response));
    }

    $query = "INSERT INTO users ( username, password, level_akses, jabatan ) VALUES ( :user, :pass, :level_akses, :jabatan ) ";

    $query_params = array(
        ':user' => $_POST['username'],
        ':pass' => $_POST['password'],
        ':level_akses' => $_POST['level_akses'],
        ':jabatan' => $_POST['jabatan']
    );

    try {
        $stmt   = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch (PDOException $ex) {

        $response["success"] = 0;
        $response["message"] = "Database Error2. Please Try Again!";
        die(json_encode($response));
    }

    $response["success"] = 1;
    $response["message"] = "Username Successfully Added!";
    echo json_encode($response);



} else {
?>
    <h1>Register</h1> 
    <form action="register.php" method="post"> 
        Username:<br /> 
        <input type="text" name="username" value="" /> 
        <br /><br /> 
        Password:<br /> 
        <input type="password" name="password" value="" /> 
        <br /><br /> 
        Level Akses:<br /> 
        <input type="text" name="level akses" value="" /> 
        <br /><br /> 
        Jabatan:<br /> 
        <input type="text" name="jabatan" value="" /> 
        <br /><br /> 
        <input type="submit" value="Register New User" /> 
    </form>
    <?php
}

?>

接下来是我的Register.java:

package id.wanda.smkkkristenimmanuelii;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Register extends Activity implements OnClickListener{

    private EditText user, pass, levelakses, jabatan;
    private Button  mRegister;

     // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();


    private static final String LOGIN_URL = "http://192.168.1.110:80/smkkimmanuel2/register.php";


    //ids
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        user = (EditText)findViewById(R.id.username);
        pass = (EditText)findViewById(R.id.password);
        levelakses = (EditText) findViewById(R.id.levelakses);
        jabatan = (EditText) findViewById(R.id.jabatan);

        mRegister = (Button)findViewById(R.id.btnRegister);
        mRegister.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

                new CreateUser().execute();

    }

    class CreateUser extends AsyncTask<String, String, String> {

         /**
         * Before starting background thread Show Progress Dialog
         * */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Register.this);
            pDialog.setMessage("Creating User...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
             // Check for success tag
            int success;
            String username = user.getText().toString();
            String password = pass.getText().toString();
            String level_akses = levelakses.getText().toString();
            String jabat = jabatan.getText().toString();

            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", username));
                params.add(new BasicNameValuePair("password", password));
                params.add(new BasicNameValuePair("level_akses", level_akses));
                params.add(new BasicNameValuePair("jabatan", jabat));


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

                //Posting user data to script
                JSONObject json = jsonParser.makeHttpRequest(
                       LOGIN_URL, "POST", params);

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

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

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

            return null;

        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (file_url != null){
                Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
            }

        }

    }

}

然后我的activity_register.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/bg_register"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="10dp" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:paddingLeft="20dp"
        android:paddingRight="20dp" >

        <EditText
            android:id="@+id/username"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/input_register_bg"
            android:hint="Masukkan Username"
            android:inputType="textCapWords"
            android:padding="10dp"
            android:singleLine="true"
            android:textColor="@color/input_register"
            android:textColorHint="@color/input_register_hint" />

        <EditText
            android:id="@+id/password"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/input_register_bg"
            android:hint="Masukkan Password"
            android:inputType="textPassword"
            android:padding="10dp"
            android:singleLine="true"
            android:textColor="@color/input_register"
            android:textColorHint="@color/input_register_hint" />

        <EditText
            android:id="@+id/levelakses"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/input_register_bg"
            android:hint="Level Akses 1-3"
            android:inputType="number"
            android:maxLength="1"
            android:padding="10dp"
            android:singleLine="true"
            android:textColor="@color/input_register"
            android:textColorHint="@color/input_register_hint" />

        <EditText
            android:id="@+id/jabatan"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/input_register_bg"
            android:hint="Masukkan Jabatan"
            android:inputType="textVisiblePassword|textNoSuggestions"
            android:padding="10dp"
            android:singleLine="true"
            android:textColor="@color/input_register"
            android:textColorHint="@color/input_register_hint" />

        <!-- Login Button -->

        <Button
            android:id="@+id/btnRegister"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:background="#ea4c88"
            android:text="@string/btn_register"
            android:textColor="@color/white" />

        <!-- Link to Login Screen -->

        <Button
            android:id="@+id/btnLinkToLoginScreen"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dip"
            android:background="@null"
            android:text="@string/btn_link_to_login"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:textSize="15dp" />
    </LinearLayout>

</LinearLayout>

0 个答案:

没有答案