Android(PHP + MySQL)中的这段代码有啥问题?

Posted

技术标签:

【中文标题】Android(PHP + MySQL)中的这段代码有啥问题?【英文标题】:What's wrong with this code in Android (PHP + MySQL)?Android(PHP + MySQL)中的这段代码有什么问题? 【发布时间】:2013-08-16 11:57:41 【问题描述】:

我的申请有问题。我正在尝试在 android 中制作注册表单,但我遇到了一些问题。

当我运行这个应用程序时,一切都很好,但是当我尝试保存数据时,它显示一个错误消息Unknown Status!,我不知道出了什么问题!

请你帮帮我。

下面是我的代码:

PS:我试过Stealz's answer,现在收到错误username exist,但我的表只有一个插入。


nota_spinner.xml

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tableLayout1"
android:layout_
android:layout_>

<TableRow
  android:id="@+id/tableRow1"
  android:layout_
  android:layout_ >

 <TextView
    android:id="@+id/textView1"
    android:layout_
    android:layout_
    android:gravity="center"
    android:text="Register Form "
    android:layout_span="1"
    android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>

<View
android:layout_
android:background="#CCCCCC" />

  <TableLayout 
    android:layout_
    android:layout_
    android:layout_weight="0.1"
    android:orientation="horizontal">

  <TextView
      android:layout_
      android:layout_
      android:text="Input Username :"
      android:textAppearance="?android:attr/textAppearanceMedium" />

  <EditText
      android:id="@+id/txtUsername"
      android:layout_
      android:layout_
      android:ems="10" >
  </EditText>

  <TextView
      android:layout_
      android:layout_
      android:text="Input Password/Confirm Password :"
      android:textAppearance="?android:attr/textAppearanceMedium" />
    <TableRow>
  <EditText
      android:id="@+id/txtPassword"
      android:layout_
      android:layout_
      android:ems="6"
      android:inputType="textPassword" >
  </EditText>
  <TextView
      android:layout_
      android:layout_
      android:text=" Again " />

  <EditText
      android:id="@+id/txtConPassword"
      android:layout_
      android:layout_
      android:ems="7"
      android:inputType="textPassword" >
  </EditText>
  </TableRow>

  <TextView
      android:layout_
      android:layout_
      android:text="Input Name :"
      android:textAppearance="?android:attr/textAppearanceMedium" />

  <EditText
      android:id="@+id/txtName"
      android:layout_
      android:layout_
      android:ems="10" >
  </EditText>

  <TextView
      android:layout_
      android:layout_
      android:text="Input Email :"
      android:textAppearance="?android:attr/textAppearanceMedium" />

  <EditText
      android:id="@+id/txtEmail"
      android:layout_
      android:layout_
      android:inputType="textEmailAddress"
      android:ems="10" >
  </EditText>

  <TextView
      android:layout_
      android:layout_
      android:text="Input Tel :"
      android:textAppearance="?android:attr/textAppearanceMedium" />

  <EditText
      android:id="@+id/txtTel"
      android:layout_
      android:layout_
      android:inputType="phone"
      android:ems="10" >
  </EditText>
 <Button
 android:id="@+id/btnSave"
android:layout_
 android:layout_
android:text="Save" />


</TableLayout >
<View
    android:layout_
    android:background="#CCCCCC" />

<LinearLayout
  android:id="@+id/LinearLayout1"
  android:layout_
  android:layout_
  android:padding="5dip" >

    <TextView
        android:id="@+id/textView2"
        android:layout_
        android:layout_
        android:text="By.. ThaiCreate.Com" />

</LinearLayout>

</TableLayout>

Class.java

public class Class extends Activity 


@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.nota_spinner);

    // 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 = "blahblah/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(Nota.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();




这是我的 php 文件 saveADDData.php

<?
$objConnect = mysql_connect("localhost","root","");
$objDB = mysql_select_db("retailer");

/*** 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 = mysql_query($strSQL);
$objResult = mysql_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 = mysql_query($strSQL);
$objResult = mysql_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 = mysql_query($strSQL);
if(!$objQuery)

    $arr['StatusID`enter code here`'] = "0"; 
    $arr['Error'] = "Cannot save data!";    

else

    $arr['StatusID'] = "1"; 
    $arr['Error'] = ""; 


/**
    $arr['StatusID'] // (0=Failed , 1=Complete)
    $arr['Error'] // Error Message
*/

mysql_close($objConnect);

echo json_encode($arr);
?>

【问题讨论】:

一个措辞糟糕的问题,它只是转储代码块,以最小的努力描述任何预期的输入和预期的输出,或列出任何试图找出原因的努力。 【参考方案1】:

据我所知,您收到错误“未知状态”,因为您收到 StatusId = 0 的响应。并且您可能会根据您的 php 在多个地方获得(用户名存在,电子邮件存在)。

我建议您为不同的错误提供不同的 statusId,例如用户名给 id=11 表示存在,电子邮件存在给 22,并在 android 端将其检查为错误,因此您可以为错误提供特定消息,而不是说未知错误,因为您知道自己遇到了什么错误。

【讨论】:

感谢您的建议。现在我收到错误“用户名存在”,但我的表只有一个插入。我不知道出了什么问题!有什么建议吗?

以上是关于Android(PHP + MySQL)中的这段代码有啥问题?的主要内容,如果未能解决你的问题,请参考以下文章

laravel手动数组分页

c++ 不清楚这段代是啥意思......

php如何用urlencode()我下面所写的这段代码进行中文加密?

我如何确定状态并在 PHP MySQL 中执行操作

Android GPS使用php在Mysql中保存当前位置

C 中的这段代码决定一个数字是不是是素数,它会因大数而崩溃。为啥?