2015-12-26 23:58
浏览 59

无法从android php连接插入MySql Db

I'm making a little MySql Crud using Android-Studio and the data fetching is working just well but I cannot insert into db and I think the problem may be because of lack of permission to write (maybe?).

Anyway, in a given point, the user is at Register.java Activity and presses button to register. This calls the method onClick() on switch case R.id.BtRegs. This calls a registerUser method which calls the ServerRequests class. In the doInBackground I try to connect to my localhost using the IP of my network lan calling the Register.php with POST method. It does not return anything from Register.php. How do I check if it is indeed a lack of permission of some other thing? I think it may be no permission because the same methods used to fetch data worked well.

Here is the part of the code on ServerRequests class which does the connection:

    protected Void doInBackground(Void... params) {

        Map<String,String> dataToSend = new HashMap<>();

        dataToSend.put("name", user.name);
        dataToSend.put("age", String.valueOf(user.age));
        dataToSend.put("username", user.username);
        dataToSend.put("password", user.password);

        String encodedStr = getEncodedData(dataToSend);
        BufferedReader reader = null;


            URL url = new URL(SERVER_ADDRESS + "/Register.php");

            HttpURLConnection con = (HttpURLConnection) url.openConnection();



            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());


And this is the Register.php which does the MySQL insert:

$con = mysqli_connect("host", "user", "pass", "db");
$name = $_POST["name"];
$age = $_POST["age"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO tabuser (name, age, username, password) VALUES (?,?,?,?) ");
mysqli_stmt_bind_param($statement, "siss", $name, $age, $username, $password);

note: Considering SERVER_ADDRESS = "http://192.168.x.x" and $con = mysqli_connect("host", "user", "pass", "db"); is normally set on main proj.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douzhengzuo7283 2016-03-17 15:29

    The problem is solved:

    As @Redbeard011010 commented, the lack of commit was causing this problem.

    So, on the code I added:

    //do the inserting
    if (!$mysqli->commit()) {
    print("Transaction commit failed

    After this, the code is working normally and the data is being inserted into the database. More info here

    点赞 打赏 评论

相关推荐 更多相似问题