-1

我还没有找到关于如何通过 php 从 android 向数据库提交数据的指南。

比如说我有以下网站:

function insert($var1) {
    // mysql inserting a new row
    $result = mysql_query("INSERT INTO report (name) VALUES ('$var1')");

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database;
        $msg = "Message received.";
    } else {
        $msg = "Not received.";
    }

    return ($msg);
}

if (isset($_POST['name'])) {
   $name = $_POST['name']);
   insert($name);   
} else {
   echo "No input.";
}

我如何从我的 Android 项目中调用它?

4

1 回答 1

1

您可以参考本教程,但您确实需要一个网络服务器。

请求机制 Android App ----> webserver ------> 数据库(mysql)

响应机制 Android App <---- webserver <----- database (mysql)

Android App 将使用JSON其他方式获取数据并显示

PHP 代码

   <?php

        $con=mysql_connect("host","username");
        if(!$con)
        {
        die("Could Not Connect".mysql_error());
        }

        $db="CREATE DATABASE login";
        mysql_query($db,$con);

        mysql_select_db("login",$con);

        $tab="CREATE TABLE info(FirstName varchar(20),LastName varchar(20))";
        mysql_query($tab,$con);

        $user_fname=$_POST['fn'];
        $user_lname=$_POST['ln'];

        $row= mysql_query("INSERT INTO info (FirstName,LastName)  VALUES('$user_fname',   '$user_lname')");
        if ($row) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";
        echo $row;
        }
        mysql_close($con);

     ?>

发送数据 (Android)

        HttpClient httpclient = new DefaultHttpClient();

        HttpPost httppost = new HttpPost("http://127.0.0.1:4001/file.php");


        List<NameValuePair> pair=new ArrayList<NameValuePair>(2);
        pair.add(new BasicNameValuePair("fn",fname));
        pair.add(new BasicNameValuePair("ln",lname));


        httppost.setEntity(new UrlEncodedFormEntity(pair));
        HttpResponse response = httpclient.execute(httppost);
于 2013-05-24T20:24:57.830 回答