gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:52:48 26 4
gpt4 key购买 nike

我想从我的 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 列插入值,但您只提供了 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()提供第三列名称,您将查询工作。

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

关于php - 无法从android应用程序将数据插入mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20823119/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com