php - 数据 POST 到 PHP 脚本时的奇怪之处

标签 php android mysql post httpclient

我使用以下代码将数据从 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 数据库中,但如果我尝试类似 echo $username 的操作,当我转到 http://xxxx/telejoke.php 时,它不会显示用户名。 .

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 对发布的数据进行处理。

最佳答案

我猜 register_globals 已关闭(这很好)!!!

您必须通过 $_POST['username'] 来寻址用户名(当然在 telepost.php 中)。

好的(在你发布你的 php 脚本之后,我想我明白了)。 您说“转到http://xxx/telejoke.php后我看不到我的用户名,但数据已正确上传”。

--> 是的,这种行为是正确的。 您没有将任何 POST 参数传递给 php 脚本,因此 $_POST['username'] 为空。

--> 但是,如果您通过应用程序调用脚本,则将所需的 POST 参数(用户名、笑话等)传递给脚本。这样它就可以将您的数据正确写入数据库。

此外,您应该优化 SQL/脚本以防止 SQL 注入(inject)。 不良用户可能会对您的网站造成损害(例如删除所有笑话等...)

关于php - 数据 POST 到 PHP 脚本时的奇怪之处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10077354/

相关文章:

php - 在链接上使用 "click"的 PHP 脚本

php - 使用命名空间和自动加载器找不到类

android - 将数据存储到我的 Sqlite 时,它​​返回我的列未创建

javascript - 为什么 showModal 在 iOS 中显示全屏?

Php 电子邮件 Mysql 获取数组

php - 搜索数组与在文本中搜索的效率......哪个更好?

android - 强制重新启动完整的应用程序以刷新 Cordova 中的包

mysql - 这个sql函数的正确版本是什么?

mysql - 如何为 mysql : Empty value for port 添加值

php - PHP PDO 语句可以接受表名或列名作为参数吗?