无法从android应用程序将数据插入mysql

时间:2013-12-29 07:40:34

标签: php android mysql

我想从我的Android应用程序中将一些数据插入到mysql数据库中,但它不起作用。我试图从模拟器和我的手机插入数据,但数据库中没有任何内容。我不知道为什么。有人可以帮帮我吗? 这是我的PHP代码

<?php
$mysqli = new mysqli("127.0.0.1", "root", "", "food");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli-    >connect_error;
}
     echo "Connected to db";

$FOOD_ID =  isset($_POST['FOOD_ID']) ? $_POST['FOOD_ID'] : null;
$FOOD_NAME = isset($_POST['FOOD_NAME']) ? $_POST['FOOD_NAME'] : null;

mysql_query ("INSERT INTO food (FOOD_ID, FOOD_NAME) VALUES('$FOOD_ID', '$FOOD_NAME')");

?>

这是java代码

public class MainActivity extends Activity {

String food_id;
String food_name;

private EditText name, id;
private Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cappuccino);

    name = (EditText) findViewById(R.id.FOOD_ID);
    id = (EditText) findViewById(R.id.FOOD_NAME);


    button = (Button) findViewById(R.id.button);

    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
           food_id = name.getText().toString();
            food_name = id.getText().toString();

            new SummaryAsyncTask().execute((Void) null);
        }
    }); 
}

class SummaryAsyncTask extends AsyncTask<Void, Void, Boolean> {

    private void postData(String idid, String namename) {

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://xxxxxx/try.php");

        try {
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
            nameValuePairs.add(new BasicNameValuePair("ID", idid));
            nameValuePairs.add(new BasicNameValuePair("NAME", namename));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
        }
        catch(Exception e)
        {
            Log.e("log_tag", "Error:  "+e.toString());
        }
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        postData(food_name,food_id);
        return null;
    }
}
}

3 个答案:

答案 0 :(得分:0)

您正在为 3 列插入值,但您提供了 2 列名称,这就是您的查询无效的原因。

见这里

mysql_query ("INSERT INTO food (FOOD_ID, FOOD_NAME) VALUES('$FOOD_ID', '$FOOD_NAME,    NOW())");
                                ^//col1  ^//col2                                       //^val3 (where is its corresponding column name ?)

解决方案:提供NOW()的第3列名称,您将查询工作。

其次,您使用的是已弃用的数据库API,即 mysql_* 函数。您需要切换为 MySQLi PDO

答案 1 :(得分:0)

列不匹配错误,您需要替换/添加*TimeCoulmnname*您的表列名称

 mysql_query ("INSERT INTO food (FOOD_ID, FOOD_NAME, *TimeCoulmnname*) VALUES('$FOOD_ID', '$FOOD_NAME,    NOW())");

注意:使用mysql_ *函数的PDO或Mysqli *函数isnetad(不建议使用)

答案 2 :(得分:0)

您使用“mysqli”连接到mySQL DB,但通过“mysql_query”函数查询它。 尝试使用“mysqli”进行连接