Flutter가 mysql 하고 결합이 까다롭네요. 정보
Flutter가 mysql 하고 결합이 까다롭네요.본문
Mysql 을 Json 으로 변경 후 Json을 찝어오는 방식인데,
대용량 mysql의 경우는 어떻게 처리할지 의문이네요.
추천
1
1
댓글 1개
우선은 PHP로 데이타를 불러와서 JSON으로 리턴하는 코드를 작성해야겠네요,
그 다음 Flutter로 List 형태로 JSON데이타를 받아서 리턴하는 함수를 작성해야겠습니다.
예제코드는 아래와 같이 작성할 수 있겠네요.
PHP코드 부분 아래 소스 복붙해서 파일로 저장해야합니다.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Run your MySQL query here
$sql = "SELECT * FROM my_table";
$result = $conn->query($sql);
$data = array();
// Loop through the result set and add each row to the data array
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
// Return the data as a JSON string
echo json_encode($data);
$conn->close();
?>
다음에는 Flutter 코드 함수 fetchData를 호출하시면
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<List<dynamic>> fetchData() async {
final response = await http.get(Uri.parse("http://yourserver.com/yourphpfile.php"));
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON string
List<dynamic> data = json.decode(response.body);
return data;
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load data');
}
}
그 다음 Flutter로 List 형태로 JSON데이타를 받아서 리턴하는 함수를 작성해야겠습니다.
예제코드는 아래와 같이 작성할 수 있겠네요.
PHP코드 부분 아래 소스 복붙해서 파일로 저장해야합니다.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Run your MySQL query here
$sql = "SELECT * FROM my_table";
$result = $conn->query($sql);
$data = array();
// Loop through the result set and add each row to the data array
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
// Return the data as a JSON string
echo json_encode($data);
$conn->close();
?>
다음에는 Flutter 코드 함수 fetchData를 호출하시면
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<List<dynamic>> fetchData() async {
final response = await http.get(Uri.parse("http://yourserver.com/yourphpfile.php"));
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON string
List<dynamic> data = json.decode(response.body);
return data;
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load data');
}
}