我正在使用以下代码将数据从 android 应用程序发布到 PHP 脚本:
public class Upload extends Activity implements OnClickListener {
EditText joke;
Button upload = (Button) findViewById(R.id.bUpload);
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.upload);
upload.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bUpload:
uploadJoke();
break;
}
}
private void uploadJoke() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxx/telejoke.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", "test"));
nameValuePairs.add(new BasicNameValuePair("joke", joke.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
此代码将数据发送到 PHP 脚本,然后将其发送到 SQL 数据库。此数据显示在 SQL 数据库中,但如果我尝试类似的操作,当我转到http://xxxx/telejoke.phpecho $username
时它不会显示用户名。
PHP 脚本:
<?php
include 'DBConnect.php';
include 'JokeValidate.php';
$username = $_POST['username'];
$joke = $_POST['joke'];
$dbname = 'Telejoke';
mysql_select_db($dbname);
echo $username. " " . $joke;
if (validate()){
$query = "INSERT INTO jokes (username, joke) VALUES ('$username','$joke')";
mysql_query($query) or die('Error, insert query failed');
}
mysql_close($conn);
?>
请帮忙。除了将其发送到数据库之外,我还想用 PHP 对发布的数据进行处理。