|
|
|
ช่วยหน่อยครับ...แก้ไม่ออก ผมกำลังทำหัวข้อ Android Add Insert Save data to Server Database (PHP+MySQL) |
|
|
|
|
|
|
|
ผมทำโค้ดตามทุกอย่างแล้ว แต่มันขึ้น Unknow Status! หาแก้มาเป็นอาทิตย์แล้ว แต่ยังแก้ไม่ได้เลยครับ...
ส่วน Code PHP MySqL มันขึ้นแบบนี้ ไม่แน่ใจว่าถูกไหม {"StatusID":"1","Error":""} แต่มัน Database Connected ได้นะครับ เพราะผมแก้ Code จาก MySql เป็น MySqli แต่ไม่แน่ใจว่าทำถูกไหม รบกวนหน่อยครับ งง ไปหมดแล้วไม่รู้ผิดตรงไหนอีก
Code saveADDData.php
Code (PHP)
<html>
<head>
<title>กำลังทดสอบ</title>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
</head>
<body>
<?php
ini_set('display_errors', 1);
error_reporting(~0);
$serverName = "localhost";
$userName = "root";
$userPassword = "root";
$dbName = "mydatabase";
$conn = mysqli_connect($serverName,$userName,$userPassword,$dbName);
mysqli_set_charset($conn, "utf8");
if (mysqli_connect_errno())
{
echo "Database Connect Failed : " . mysqli_connect_error();
}
else
{
echo "Database Connected เข้าได้เว้ยเห้ย !!.";
echo "<br>";
echo "Server Date/Time : ".date("Y-m-d H:i:s"); echo "<br>"; echo "<br>";
}
/*** for Sample
$_POST["sUsername"] = "a";
$_POST["sPassword"] = "b";
$_POST["sName"] = "c";
$_POST["sEmail"] = "d";
$_POST["sTel"] = "e";
*/
$strUsername = @$_POST["sUsername"];
$strPassword = @$_POST["sPassword"];
$strName = @$_POST["sName"];
$strEmail = @$_POST["sEmail"];
$strTel = @$_POST["sTel"];
/*** Check Username Exists ***/
$strSQL = "SELECT * FROM member WHERE Username = '".$strUsername."' ";
$objQuery = $conn -> query($strSQL);
$objResult = mysqli_fetch_array($objQuery);
if($objResult)
{
$arr['StatusID'] = "0";
$arr['Error'] = "Username Exists!";
echo json_encode($arr);
exit();
}
/*** Check Email Exists ***/
$strSQL = "SELECT * FROM member WHERE Email = '".$strEmail."' ";
$objQuery = $conn -> query($strSQL);
$objResult = mysqli_fetch_array($objQuery);
if($objResult)
{
$arr['StatusID'] = "0";
$arr['Error'] = "Email Exists!";
echo json_encode($arr);
exit();
}
/*** Insert ***/
$strSQL = "INSERT INTO member (Username,Password,Name,Email,Tel)
VALUES (
'".$strUsername."',
'".$strPassword."',
'".$strName."',
'".$strEmail."',
'".$strTel."'
)
";
$objQuery = $conn -> query($strSQL);
if(!$objQuery)
{
$arr['StatusID'] = "0";
$arr['Error'] = "Cannot save data!";
}
else
{
$arr['StatusID'] = "1";
$arr['Error'] = "";
}
/**
$arr['StatusID'] // (0=Failed , 1=Complete)
$arr['Error'] // Error Message
*/
mysqli_close($conn);
echo json_encode($arr);
?>
</body>
</html>
ส่วนนี้ Code MainActivity.java
Code (Android-Java)
package com.example.satta.water;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// btnSave
final Button btnSave = (Button) findViewById(R.id.btnSave);
// Perform action on click
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(SaveData())
{
// When Save Complete
}
}
});
}
public boolean SaveData()
{
// txtUsername,txtPassword,txtName,txtEmail,txtTel
final EditText txtUsername = (EditText)findViewById(R.id.txtUsername);
final EditText txtPassword = (EditText)findViewById(R.id.txtPassword);
final EditText txtConPassword = (EditText)findViewById(R.id.txtConPassword);
final EditText txtName = (EditText)findViewById(R.id.txtName);
final EditText txtEmail = (EditText)findViewById(R.id.txtEmail);
final EditText txtTel = (EditText)findViewById(R.id.txtTel);
// Dialog
final AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setTitle("Error! ");
ad.setIcon(android.R.drawable.btn_star_big_on);
ad.setPositiveButton("Close", null);
// Check Username
if(txtUsername.getText().length() == 0)
{
ad.setMessage("Please input [Username] ");
ad.show();
txtUsername.requestFocus();
return false;
}
// Check Password
if(txtPassword.getText().length() == 0 || txtConPassword.getText().length() == 0 )
{
ad.setMessage("Please input [Password/Confirm Password] ");
ad.show();
txtPassword.requestFocus();
return false;
}
// Check Password and Confirm Password (Match)
if(!txtPassword.getText().toString().equals(txtConPassword.getText().toString()))
{
ad.setMessage("Password and Confirm Password Not Match! ");
ad.show();
txtConPassword.requestFocus();
return false;
}
// Check Name
if(txtName.getText().length() == 0)
{
ad.setMessage("Please input [Name] ");
ad.show();
txtName.requestFocus();
return false;
}
// Check Email
if(txtEmail.getText().length() == 0)
{
ad.setMessage("Please input [Email] ");
ad.show();
txtEmail.requestFocus();
return false;
}
// Check Tel
if(txtTel.getText().length() == 0)
{
ad.setMessage("Please input [Tel] ");
ad.show();
txtTel.requestFocus();
return false;
}
String url = "http://localhost/android/saveADDData.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sUsername", txtUsername.getText().toString()));
params.add(new BasicNameValuePair("sPassword", txtPassword.getText().toString()));
params.add(new BasicNameValuePair("sName", txtName.getText().toString()));
params.add(new BasicNameValuePair("sEmail", txtEmail.getText().toString()));
params.add(new BasicNameValuePair("sTel", txtTel.getText().toString()));
/** Get result from Server (Return the JSON Code)
* StatusID = ? [0=Failed,1=Complete]
* Error = ? [On case error return custom error message]
*
* Eg Save Failed = {"StatusID":"0","Error":"Email Exists!"}
* Eg Save Complete = {"StatusID":"1","Error":""}
*/
String resultServer = getHttpPost(url,params);
/*** Default Value ***/
String strStatusID = "0";
String strError = "Unknow Status!";
JSONObject c;
try {
c = new JSONObject(resultServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Error");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Prepare Save Data
if(strStatusID.equals("0"))
{
ad.setMessage(strError);
ad.show();
}
else
{
Toast.makeText(MainActivity.this, "Save Data Successfully", Toast.LENGTH_SHORT).show();
txtUsername.setText("");
txtPassword.setText("");
txtConPassword.setText("");
txtName.setText("");
txtEmail.setText("");
txtTel.setText("");
}
return true;
}
public String getHttpPost(String url,List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
}
อันนี้เป็น Code Build.gradle
Code (Android-Java)
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.example.satta.water"
minSdkVersion 19
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
useLibrary 'org.apache.http.legacy'
}
configurations {
all {
exclude module: 'httpclient'
exclude module: 'commons-logging'
}
}
dependencies {
compile 'org.apache.httpcomponents:httpclient:4.5.5'
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
ผมก็แก้ตรงส่วนที่ชี้ไปยังไฟล์ PHP MySql แล้ว เป็นแบบนี้ String url = "http://localhost/android/saveADDData.php";
Tag : Mobile, MySQL, Android, Mobile
|
ประวัติการแก้ไข 2018-03-28 21:05:25 2018-03-29 08:50:25
|
|
|
|
|
Date :
2018-03-28 21:03:59 |
By :
mr.satta |
View :
1218 |
Reply :
2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ลบ code นี้ออกแล้วก็ยังขึ้น {"StatusID":"0","Error":"Username Exists!"} เหมือนเดิม
<html>
<head>
<title>กำลังทดสอบ</title>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
</head>
<body>
และก็ยังขึ้นไม่รู้จักสถานะ ตามภาพเดิมครับ
|
|
|
|
|
Date :
2018-03-30 14:30:45 |
By :
mr.satta |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 02
|