我在从 mysql 检索数据时遇到问题。我的程序中有两种选择语句。
一种是“Select * From abcTable;” 另一个是“Select * From abcTable WHERE attribute = 'abc';”
该程序适用于第一个,但第二个有错误。
在调用 mysql 之前,我输出了查询结构,它在 phpMyAdmin 中工作。转到 php 脚本后..查询回显完全不同。这是代码
我以这种格式构造查询并传递给 query_string
String query = "SELECT * FROM abcTable WHERE attribute = \'" + attributeVariable + \';"
调用mysql函数(这里的query_string没有问题,即“Select * From abcTable WHERE attribute = 'abc';”)
//Call PHP Server to execute query
public static String executeQuery(String query_string) {
String result = "";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/getdata2.php");
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("query_string", query_string));
System.out.println("GO TO?????" + query_string);
System.out.println("GO TO PARAM???" + params);
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
//view_account.setText(httpResponse.getStatusLine().toString());
HttpEntity httpEntity = httpResponse.getEntity();
InputStream inputStream = httpEntity.getContent();
BufferedReader bufReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder builder = new StringBuilder();
String line = null;
while((line = bufReader.readLine()) != null) {
builder.append(line + "\n");
}
inputStream.close();
result = builder.toString();
} catch(Exception e) {
Log.e("log_tag", e.toString());
}
return result;
}
php 脚本($query 变为“Select * From abcTable WHERE attribute = \'abc\';”)
<?php
/* Change database details according to your database */
$dbConnection = mysqli_connect('localhost', 'name', 'pw', 'dbname');
$query = $_POST['query_string'];
$result = mysqli_query($dbConnection, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$output[] = $row;
}
print(json_encode($output));
} else {
print($query);
}
?>
并且错误显示
01-20 05:01:48.687: I/System.out(359): <b>Warning</b>: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in <b>C:\AppServ\www\getdata2.php</b> on line <b>6</b><br />
非常感谢您的帮助!!!!