【问题标题】:Edittext value not being detected by PHP script to upload to Sql Server remote databasePHP脚本未检测到Edittext值以上传到Sql Server远程数据库
【发布时间】:2014-05-28 09:37:43
【问题描述】:

我正在开发一个通过 PHP 脚本连接到外部 SQLServer 2008 数据库的 Android 应用程序,记住我是 PHP 新手

我试图从一周开始通过 PHP 脚本将一个动态值(edittext 值)从 android 插入外部数据库,但一切都是徒劳的。我已经设法通过 PHP 脚本连接到数据库,但是它没有插入 edittext 值。显然,它没有将值从 android 发送到 php 变量。我已经尝试了几乎所有教程,但并不快乐。我确定我在某个地方犯了错误,但不知道在哪里。任何帮助或指出正确的方向将不胜感激。

PHP 脚本(验证并在 Manufacturer_name 和 Manufacturer_companies_id 列中插入值)

if (!empty($_POST['manufacturers_name']) && !empty($_POST['manufacturers_companies_id']))
    {
        $man_Name = $_POST['manufacturers_name'];
        $man_com_id= $_POST['manufacturers_companies_id'];
        $sql="INSERT INTO tbl_manufacturers (manufacturers_name, manufacturers_companies_id)";
        $sql.=" VALUES ('"._FormatStr4Qry($_POST[$man_Name])."','"._FormatStr4Qry($_POST[$man_com_id])."')";
            if ($res=sqlsrv_query($db,$sql,array(),array("Scrollable"=>'static')))
                { 
                    // successfully inserted into database
                    $response["success"] = 1;
                    $response["message"] = "Product successfully created.";

                    // echoing JSON response
                    echo json_encode($response);
                } 
            else 
                {
                    // failed to insert row
                    $response["success"] = 0;
                    $response["message"] = "Oops! An error occurred.";

                    // echoing JSON response
                    echo json_encode($response);
                }
            sqlsrv_close($db);
    }   
    else
        {
        // successfully inserted into database
        $response["success"] = 0;
        $response["message"] = "fill in required fields.";

        // echoing JSON response
        echo json_encode($response);
        }

PHP 执行:

{"success":0,"message":"fill in required fields."}

JSON 解析器

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // 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();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "UTF_8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            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, "UTF_8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } 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;

}

CreateNewAppliance 类

public class CreateNewAppliance extends Activity {

// Progress Dialog
private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();
EditText inputManufacturersName;
String manufacturersName;

// url to create new product
private static String url_create_product = "http://datanetbeta.multi-trade.co.uk/tablet/writeManufacturers.php";


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.createnewappliance);

    // Edit Text
    inputManufacturersName = (EditText) findViewById(R.id.etManName);
    // Create button
    Button btnCreateAppliance = (Button) findViewById(R.id.btnAddNewAppliance);

    // button click event
    btnCreateAppliance.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // creating new product in background thread
            new NewAppliance().execute(inputManufacturersName.getText().toString());
        }
    });
}

/**
 * Background Async Task to Create new product
 * */
class NewAppliance extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(CreateNewAppliance.this);
        pDialog.setMessage("Creating Appliance..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Creating product
     * */
    protected String doInBackground(String... strings) {
        manufacturersName = inputManufacturersName.getText().toString().trim();
        System.out.println(manufacturersName);  //check if the value is being outputted

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>(1);
        params.add(new BasicNameValuePair("manufacturers_name", manufacturersName));

        Log.e("manufacturers_name",strings[0]); // check if
        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "POST", params);

        // check log cat fro response
        Log.d("Create Response", json.toString());

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();
    }

}

}

Android 执行:

05-28 10:35:01.929: I/System.out(6771): hdhdhdhdhdh
05-28 10:35:01.939: E/manufacturers_name(6771): hdhdhdhdhdh
05-28 10:35:01.994: D/ProgressBar(6771): updateDrawableBounds: left = 0
05-28 10:35:01.994: D/ProgressBar(6771): updateDrawableBounds: top = 0
05-28 10:35:01.994: D/ProgressBar(6771): updateDrawableBounds: right = 96
05-28 10:35:01.994: D/ProgressBar(6771): updateDrawableBounds: bottom = 96
05-28 10:35:04.814: D/Create Response(6771): {"message":"fill in required fields.","success":0}
05-28 10:35:04.924: E/ViewRootImpl(6771): sendUserActionEvent() mView == null

【问题讨论】:

    标签: php android sql-server


    【解决方案1】:

    您希望 PHP 脚本中有两个参数,而您只传递一个参数。

      if (!empty($_POST['manufacturers_name']) && !empty($_POST['manufacturers_companies_id']))
    

    您还需要按照现在写的方式传递manufacturers_companies_id。

    使用简单的 Http 客户端测试脚本,并确保您具备使其工作的一切。然后修改android代码。

    祝你好运

    【讨论】:

    • 感谢好友回复。我已经对 Android 代码进行了所有必要的修改。你能告诉我如何用“简单”的HttpClient测试脚本吗?就像我以前做过的那样。
    • 有很多工具可以提供帮助。邮递员soapui (getpostman.com)。谷歌搜索,你可以找到很多(google.com/#q=http%20post%20plugin
    • 嗨 Raghu,我已经设法在简单的 HttpClient 中对其进行了测试,并且脚本运行良好。根据您的建议,PHP 代码正在获取数据但不显示文本是数据库列,但是数据库中的条目将显示为空白并带有新的 ID。你能告诉我哪里出错了吗:)。
    • 我不太了解 PHP,但您正在阅读 $_POST 两次。 $sql.=" VALUES ('"._FormatStr4Qry($_POST[$man_Name])."','"._FormatStr4Qry($_POST[$man_com_id])."')";上一行,删除 $_POST。您已经拥有 man_Name 和 man_com_id 中的值。直接使用就好了。
    • 我很抱歉成为 PHP 的初学者,但利用我的主动性和您的帮助,我正在尽我所能。你的意思是把它改成... $sql.=" VALUES ('"._FormatStr4Qry($man_Name)."','"._FormatStr4Qry($man_com_id).‌​"')";
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 2020-08-29
    相关资源
    最近更新 更多