【发布时间】: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