How to connect flutter to localhost mysql database How to connect flutter to localhost mysql database dart dart

How to connect flutter to localhost mysql database


A connection directly to MySQL (or any other database access directly from clients) is not a good idea, except Firebase. If you want to interact with the MySql db a better solution is to create a server app and expose some HTTP REST API (with node.js, php ect.). With the API you can provide also a token for the client in order to access your data.You can make HTTP requests https://api.dartlang.org/stable/1.24.3/dart-io/HttpClient-class.html.

Now if for any reason you want still to connect directly to MySQL just keep in mind that any client application can access your DB with write permission in this case (and this is not a good practice at all!) just for a test example you can try creating a php file:

// Connect and insert data example

<?php     if (isset($_POST["value"])) {        $servername = "localhost";        $user = "username";        $pw = "password";        $db = "data";        #Connect to Server        $con = new Mysqli($servername, $user, $pw, $db) or die(Mysqli_errno());        $value =htmlspecialchars(stripslashes(trim($_POST["value"])));        $sql = $con->prepare("INSERT INTO tableName (value) VALUES ('$value')");        $result = $sql->execute();        if ($result) {            echo "Success";        }        else {            echo "Failed";        }        $con->close();    }     else {       echo "Not found";    } ?>

Also need to write the flutter part that make the request on http.post

void post() async {    var result = await http.post(        "http://{your url}/index.php",         body: {           "value": "Test DB Connection"         }    );    print(result.body);}