如果code = 1,则插入成功。如果code = 0,则插入是 不成功。我不能这样。我想在android屏幕上看到这些信息。我很抱歉我的英语不好。如果你能提供帮助我会很高兴。
php代码:
<?php
$host='123.45.67.89';
$uname='username';
$pwd='password';
$db="database";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$name=$_REQUEST['name'];
$surname=$_REQUEST['surname'];
$age=$_REQUEST['age'];
$flag['code']=0;
if($r=mysql_query("insert into table values('$name','$surname','$age') ",$con))
{
$flag['code']=1;
echo"hi";
}
print(json_encode($flag));
mysql_close($con);
?>
Java代码:
insert.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
name=editText1.getText().toString();
surname=editText2.getText().toString();
age=editText3.getText().toString();
String data[]={name,surname,age};
new DoThatThingBro().execute(data);
}
});
}
protected JSONObject addPost(String name, String surname, String age) throws ClientProtocolException, IOException, JSONException{
String URL = "http://website.com/insert.php?name="+name+"&surname="+surname+"&age="+age;
HttpClient httpclient = new DefaultHttpClient();
HttpGet get = new HttpGet(URL);
HttpResponse response = httpclient.execute(get);
StatusLine status = response.getStatusLine();
s = status.getStatusCode();
if(s == 200){
HttpEntity e = response.getEntity();
String data = EntityUtils.toString(e);
JSONArray posts = new JSONArray(data);
JSONObject result = posts.getJSONObject(0);
return result;
}
return null;
}
public class DoThatThingBro extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = addPost(params[0],params[1],params[2]);
String data = json.getString("reuslt");
return data;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
答案 0 :(得分:0)
在你的php中试试这样的代码。当你想看表时叫它。
$result = mysqli_query($con,"SELECT * FROM tablename");
将表存储在$ result变量中。
while($row = mysqli_fetch_array($result)) {
echo $row['firstcolumn'] . " " . $row['secondcolumn'];
echo "<br>";
}
这会将表中的所有数据作为数组获取并打印所有结果,直到没有其他内容可以打印。 希望这有帮助。让我知道。
答案 1 :(得分:0)
编辑:评论后,问题更加明确。
将你的php设置为:
$r = mysql_query("insert into table values('$name','$surname','$age') ",$con)
if (!$r) {
echo "Insert failed: " . mysql_error());
} else {
$flag['code']=1;
echo "Successfully inserted " . mysql_affected_rows() . " rows";
}
你的java:
String URL = "http://website.com/insert.php?name="+name+"&surname="+surname+"&age="+age;
HttpClient httpclient = new DefaultHttpClient();
HttpGet get = new HttpGet(URL);
try {
String response = httpclient.execute(get, new BasicResponseHandler());
Toast.makeText(this, response, Toast.LENGTH_LONG);
} catch (IOException e) {
e.printStackTrace();
}