好的,我需要根据一些参数从在线数据库中检索特定字段 参数必须从Android应用程序传递到PHP脚本(我有一个参数,但它失败多个)。
PHP脚本
<?php error_reporting (E_ALL ^ E_NOTICE); ?>
<?php
$username = "root";
$password = "";
$host = "localhost";
$dbname = "db.projectblue";
$chapter = mysql_real_escape_string($_POST['column']);
$id = mysql_real_escape_string($_POST['id']);
mysql_connect($host, $username, $password);
mysql_select_db($dbname);
$q=mysql_query("SELECT '$column' FROM tblphysics WHERE id='$id'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
如您所见,必须根据输入动态创建SQL查询。如果我用一个明确的列名替换$ column变量,如版本或章节,但它不适用于变量。
这是我的JAVA代码
private JSONObject getJSONObject(int id, String column) {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("column", column));
nameValuePair.add(new BasicNameValuePair("id", Integer.toString(id)));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(PARSER_URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e(LOG_TAG_JSON, "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = jArray.getJSONObject(0);
return json_data;
} catch (JSONException e) {
Log.e(LOG_TAG_JSON, "Error parsing data " + e.toString());
}
return null;
}
我正在调用私有方法
public String getChapter(int id) throws JSONException {
JSONObject object = getJSONObject(id, "chapter");
String iChapter = object.optString("chapter");
return iChapter;
}
当我用PHP脚本中的两个变量调用这个公共方法时,输出(从另一个方法记录)是这样的:
Version (this is a column name in db) : 0 (should be 5)
Chapter (this is a column name in db) : chapter (should be newton)
我的问题是:
为什么php脚本不能使用多个变量?
我的NameValuePair设置正确吗?
是否甚至可以创建具有动态列名和/或表名的SQL查询?
编辑: 修复很简单,我甚至没有看到它。我在查询中有$ column而不是$ chapter,查询中的变量必须是“。$ chapter。”
答案 0 :(得分:0)
提示提示:在查询之前为什么不尝试回显$ column并查看存储在$ column中的值。
您可以参考此示例并清除一些疑问 http://sarangasl.blogspot.com/2011/06/android-login-screen-using-httpclient.html