簡體   English   中英

從MySQL檢索數據到React Native時獲取速度慢

[英]Slow fetch when retrieving data from MySQL to React Native

我不確定是什么原因導致讀取速度太慢。 可能是React Native的獲取,還是我的查詢設置方式?

這是我對React Native的獲取:

    forceUpdateHandler(){
  fetch(`https://www.example.com/React/user-profile.php?username=${this.state.username}` , {
  method: 'GET',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  }

 })
   .then((response) => response.json())
   .then((responseJson) => {
     this.setState({
       isLoading: false,
       dataSource: responseJson,
       user_image:  responseJson[0].user_images.map(item => ({ ...item, progress: new Animated.Value(0), unprogress: new Animated.Value(1) })),
       },function() {


       });
   })
   .catch((error) => {
     //console.error(error);
   });
}

這是我對mysql的PHP查詢:

 if ($conn->connect_error) {

 die("Connection failed: " . $conn->connect_error);
} 
 // Getting the received JSON into $json variable.
 $json = file_get_contents('php://input');

 // decoding the received JSON and store into $obj variable.
 $obj = json_decode($json,true);

// Populate Username from JSON $obj array and store into $username.
$username = $_GET['username'];

$result = mysqli_query($conn, "SELECT * FROM users WHERE username='$username'");
$fetch = mysqli_query($conn, "SELECT id, images, note, date FROM user_images WHERE username='$username' ORDER BY date DESC"); 

// I think, you'll get a single row, so no need to loop
$json = mysqli_fetch_array($result, MYSQL_ASSOC);

$json2 = array();
while ($row = mysqli_fetch_assoc($fetch)){
    //Our YYYY-MM-DD date.
    $ymd = $row['date'];

    //Convert it into a timestamp.
    $timestamp = strtotime($ymd);

    //Convert it to DD-MM-YYYY
    $dmy = date("m/d/Y", $timestamp);
    $json2[] = array(
        'id' => $row["id"],
        'images' => $row["images"],
        'note' => $row["note"],
        'date' => $dmy,

    );
}
$json['user_images'] = $json2;
echo json_encode(array($json));
$conn->close();

該數據只有5列數據,但是當我將其限制為1時,react native會快速獲取數據。 有沒有一種方法可以在我仍然擁有所有數據結果的同時加快獲取速度?

  1. 您應該在用戶表的用戶名列上具有唯一索引。 您也可以假設只有一行會返回。 而且它也會更快,因為MySQL在找到一條記錄時會返回。
  2. (我沒注意到OP在MyISAM上。)看來您的表已被刪除,並且您正在使用用戶名進行查詢。 如果更改用戶名怎么辦? 您將更新user_images表嗎?
  3. 您的user_images表應具有一個auto_increment主鍵,以便您的order by可以按id desc而不是日期進行排序。 您可以在用戶名上有一個索引,但這還取決於您對where語句的選擇性。 如果用戶名的基數非常低,則MySQL將選擇全表掃描。
  4. 您還應該嘗試通過一個查詢(聯接)而不是兩個查詢來獲取數據。
  5. 您應該使用准備好的語句來防止SQL注入。 您的代碼現在容易受到攻擊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM