0

Can i pass data which is stored from a flutter variable to php variable that will be the value of the POST method so that it will be used for MySQL query?

flutter code


var myemail = email.text;

and it will be passed to:

php code:

$email = $_POST['myemail'];

so far I have tried this:

 var url = Uri.parse("http://192.168.1.6/getdata.php");
 var response = await http.post(url, body: {
 "email": email.text,
 "password": password.text,
  });

thank you

  • 3
    Yes you can do that. You can send it in a HTTP request from the flutter app to the PHP app. Are you stuck on anything specific? have you done any research, or tried any code? See also [ask] – ADyson Apr 04 '23 at 16:06
  • yes, i'm stuck in connecting my flutter app to mysql database. my login screen is not working. done a lot of research but no progress – Rommel Pabustan Apr 04 '23 at 16:08
  • "not working" in what way exactly? What happens when you run that http.post method? What's in $_POST in PHP as a result? – ADyson Apr 04 '23 at 16:20
  • it seems that my query is not working because i wasn't able to redirect to the next screen though i'm entering the correct user credentials for the login screen – Rommel Pabustan Apr 04 '23 at 16:48
  • That doesn't answer the specific question I asked. Have you actually done any proper, detailed debugging? – ADyson Apr 04 '23 at 16:52
  • yes, it looks like the value of my textfield in flutter are not getting to the php post method though i'm connected to my databse and the problem is with the http.post – Rommel Pabustan Apr 04 '23 at 16:56
  • So, when you debugged it, what _exactly_ was in $_POST, and how did you check it? e.g. you could log it with `file_put_contents("log.txt", print_r($_POST, true));` to see the contents. I note that in your current code, for example, you are looking for `$_POST['myemail'];` but in your flutter code there is no such parameter - you sent `email`, not `myemail`. – ADyson Apr 04 '23 at 16:59
  • i changed my variable now but i think the $_POST is empty – Rommel Pabustan Apr 04 '23 at 17:11
  • you "think"...because? You don't need to guess...just actually log it. – ADyson Apr 04 '23 at 17:13
  • the $_POST is empty and not getting the values of my flutter textfileds – Rommel Pabustan Apr 04 '23 at 17:23
  • What is the actual, specific output of the command I showed you, inside the text file? Can we start being specific and precise please, instead of giving vaguer descriptions. It makes it very hard to know if you've actually done precisely what was asked, or something else less useful. – ADyson Apr 04 '23 at 17:36
  • The reason I say this is because the flutter and PHP code look like they should be correct in terms of sending and receiving the data, other than the `email/myemail` typo I already pointed out above – ADyson Apr 04 '23 at 18:01
  • the content of the log.txt is this: Array() – Rommel Pabustan Apr 05 '23 at 05:09
  • Thankyou. That is very useful, although the result is a bit surprising. Now please try, instead of that, `file_put_contents("test.txt", file_get_contents('php://input'));` and tell me what it puts into to the test.txt file when you send the flutter request. – ADyson Apr 05 '23 at 08:29
  • when i run the flutter app and click on the button, it doesn't create the test.txt file but i run phpmyadmin and directly type the url together the php file (getdata.ph) that's the time it creates the test.txt file but the file is empty. meaning flutter is not really connecting to my php file – Rommel Pabustan Apr 05 '23 at 14:24
  • ok. So then you have to debug the flutter code, and find out what happened to the connection. Maybe an error is returned or something. I am not a flutter expert but I assume it has debugging / logging tools that you can use to get more information about what happens to the connection attempt. – ADyson Apr 05 '23 at 15:16
  • Ok I'll check l.thank you – Rommel Pabustan Apr 06 '23 at 03:16

1 Answers1

-1

You can use http to post data to PHP

 Future<void> sendData() async {
   var url = Uri.parse('http://localhost/getdata.php');
   var response = await http.post(url, body: {
     'email': myemail,
     'password': password.text,
   });
 
   if (response.statusCode == 200) {
     print('Data sent successfully: ${response.body}');
   } else {
     print('Failed to send data. Status code: ${response.statusCode}');
   }
 }

You'll need to install and import http import 'package:http/http.dart' as http; and dependencies: http: ^0.13.3

And the PHP part

 <?php
 // Set correct content type
 header('Content-Type: application/json');
 
 // Connect to your MySQL database
 $servername = "localhost";
 $username = "username";
 $password = "password";
 $dbname = "your_database_name";
 
 $conn = new mysqli($servername, $username, $password, $dbname);
 
 if ($conn->connect_error) {
   die(json_encode(['error' => 'Failed to connect to the      database']));
 }
 
 // Get POST data
 $email = $_POST['email'];
 $password = $_POST['password'];
 
 // Perform your MySQL query (e.g., insert, update, or search)
 $query = "INSERT INTO users (email, password) 
 VALUES ('$email', '$password')";
 
 if ($conn->query($query) === TRUE) {
   echo json_encode(['success' => 'Data inserted successfully']);
 } else {
   echo json_encode(['error' => 'Failed to insert data']);
 }
 
 $conn->close();
 ?>
 
Bellash
  • 7,560
  • 6
  • 53
  • 86
  • thank you Bellash but the codes you provided is not working – Rommel Pabustan Apr 04 '23 at 16:46
  • failed to send data – Rommel Pabustan Apr 04 '23 at 16:49
  • did you update the url to match your server ? – Bellash Apr 04 '23 at 16:52
  • yes, i replaced it with my localhost url – Rommel Pabustan Apr 04 '23 at 16:54
  • **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unparameterised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Apr 04 '23 at 17:11
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. If you learnt your current technique from a tutorial or book, please don't use that resource again. – ADyson Apr 04 '23 at 17:11
  • Also, please don't store passwords in plain text - that is another security risk. Learn about [password hashing](https://www.php.net/manual/en/faq.passwords.php) instead. See also [How to use PHP's password_hash to hash and verify passwords](https://stackoverflow.com/questions/30279321/how-to-use-phps-password-hash-to-hash-and-verify-passwords). Even if this is just an example, don't post bad examples. P.S. The original question is just about the problem with posting the data from flutter to PHP, so arguably there was no need to show anything about the database bit at all anyway! – ADyson Apr 04 '23 at 17:11
  • Oh, and also please bring your error handling into the 21st century. Add `mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);` before your `mysqli_connect()` (or `new mysqli()`) command, and this will ensure that errors with your SQL queries are reported correctly to PHP automatically. That way you don't need to clutter your script with repetitive code to keep checking errors after every mysqli command. And you should never be echoing error data deliberately - it can easily reveal sensitive info to attackers by accident. – ADyson Apr 04 '23 at 17:12
  • yes that's why i only used an example – Rommel Pabustan Apr 04 '23 at 17:16
  • Like I said though, just don't post bad examples. Because people see it in a stackoverflow answer and take it seriously. I would just remove that part. Or you can fix it of course :-) – ADyson Apr 04 '23 at 19:35