1

I am trying to connect database from my flutter app and I want to post value that I wrote in textfield to database. I wrote some code but I cannot post to database, it is giving me error. I guess I have to edit my php code but I don't know how I can edit, please help me... the codes and errors below here

     Future<List> sendData() async {
   await http.post(
      "https://www.ekspar.com/trying/go.php",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: {
        "adi": nameController.text,
        "soyadi": surnameController.text,
      },
    );
    
    json.decode(response.body);
  }

@override
  void initState() {
    sendData();
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Theme.of(context).backgroundColor,
        body: Scaffold(
          appBar: AppBar(
            title: Text("Register"),
          ),
          body: Container(
            child: Center(
              child: Column(
                children: <Widget>[
                  Text(
                    "ad",
                    style: TextStyle(fontSize: 18.0),
                  ),
                  TextField(
                    controller: nameController,
                    decoration: InputDecoration(hintText: 'ad'),
                  ),
                  Text(
                    "soyad",
                    style: TextStyle(fontSize: 18.0),
                  ),
                  TextField(
                    controller: surnameController,
                    decoration: InputDecoration(hintText: 'soyad'),
                  ),
                  RaisedButton(
                    child: Text("Register"),
                    onPressed: () {
                      setState(() {
                        _build();
                      });
                      sendData();
                    },
                  ),
                  _build()
                ],
              ),
            ),
          ),
        )

        //(_buildBody(),
        );
  }

and PHP:

<?
include("begin.php");
include("functions-develop.php");
$adi = $_POST['adi'];
$soyadi =$_POST['soyadi'];
if ($adi and $soyadi) {
$query = $func->query("insert into `dart` (`adi`, `soyadi`) VALUES ('$adi','$soyadi')");
echo "Kayit Eklenmiştir";
}
else
{
echo "Bos veri";
}
?>

and error:

[VERBOSE-2:ui_dart_state.cc(166)] Unhandled Exception: FormatException: Unexpected character (at character 1)
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
^
#0      _ChunkedJsonParser.fail  (dart:convert-patch/convert_patch.dart:1404:5)
#1      _ChunkedJsonParser.parseNumber  (dart:convert-patch/convert_patch.dart:1271:9)
#2      _ChunkedJsonParser.parse  (dart:convert-patch/convert_patch.dart:936:22)
#3      _parseJson  (dart:convert-patch/convert_patch.dart:40:10)
#4      JsonDecoder.convert  (dart:convert/json.dart:505:36)
#5      JsonCodec.decode  (dart:convert/json.dart:156:41)
#6      jsonDecode  (dart:convert/json.dart:96:10)
#7      _LoginScreenState.sendData 
package:ekspar/screens/login.dart:357
<asynchronous suspension>
#8      _LoginScreenState.initState 
package:ekspar/screens/login.dart:373
#9      StatefulElement._firstBuild 
package:flutter/…/widgets/framework.dart:4684
#10     ComponentElement.mount 
package:flutter/…/widgets/framework.dart:4520
#11     Element.infl<…>

i am doing wrong but where I don't know...

4
  • You have json.decode(response.body); when your PHP just ouputs strings, not json. Either remove the json.decode() or output the result as valid json. Commented Jun 30, 2020 at 12:05
  • Warning! You are wide open for SQL injection attacks! You should use parameterized prepared statements instead of using completely unescaped user data directly in your database queries like that. Never ever ever never trust user input. Commented Jun 30, 2020 at 12:06
  • I tried to remove the json.decode() but still it doesn't post anything to database... Commented Jun 30, 2020 at 12:14
  • Don't use short tags <? since they have been disabled as default since a bunch of versions back. Use <?php. What does the $func variable contain? PDO? MySQLi? A custom DB class? Do you have any error logging for failed queries? Also, since you're not escaping the post data at all before injecting it into the query, a single ' would break your query. Please share all relevant PHP code. If you post to your PHP endpoint directly from Postman or similar, what do you get? Have you checked the web servers error log? Please share all relevant code and debugging info. Commented Jun 30, 2020 at 12:24

1 Answer 1

1

Taking a look at your API makes me think that you are trying to post data. At the same time, I can see that you are using a get request in your flutter app.

If you are trying to post data then make a POST request from your flutter app rather then a GET request.

Here's an example of POST request in flutter using the HTTP package.

Sample POST request:

String url = "https://www.ekspar.com.tr/onarim/post.php";
var response = await http.post(url, body: {
    "adi":"YOUR_DATA",
    "soyadi":"YOUR_DATA"
});

var body = jsonDecode(response.body);

if(response.statusCode == 200){
    debugPrint("Data posted successfully");
}else{
    debugPrint("Something went wrong! Status Code is: ${response.statusCode}");
}
Sign up to request clarification or add additional context in comments.

2 Comments

@Rasat if you've tried it before then please kindly consider updating your question with the updated code.
@Rasat After looking at the updated code, I found that you are sending body: { "adi": nameController.text, "soyadi": surnameController.text, }; which is wrong. HTTP package expects data inside quotes (""). Consider replacing your current code with this. body: { "adi": "${nameController.text}", "soyadi": "${surnameController.text}", },

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.