【问题标题】:Slow fetch when retrieving data from MySQL to React Native从 MySQL 检索数据到 React Native 时获取缓慢
【发布时间】:2019-01-23 23:01:12
【问题描述】:

我不确定是什么导致提取速度如此缓慢。也许这可能是 React Native 的 fetch 或者是我的查询设置方式?

这是我对 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 端会快速获取数据。有没有一种方法可以加快获取速度,同时仍然拥有所有数据结果?

【问题讨论】:

  • 您是否尝试过独立测试 PHP 代码?你可以测试一个请求需要多长时间。您可能需要为表添加索引以提高性能。
  • 你能解释一下限制为 1 吗?是否限制服务器端只返回一个结果?
  • @BrianGerhards 我实际上只是现在,当我插入一些东西时,它比这个查询快得多。我如何索引这个?它的表类型是 MyISAM
  • @BrianGerhards 是的,没错

标签: php mysql reactjs react-native fetch


【解决方案1】:
  1. 您应该在用户表的用户名列上有唯一索引。这也将消除您的假设,即只有一行会返回。而且它也会更快,因为 MySQL 会在找到一条记录时返回。
  2. (我没有注意到 OP 在 MyISAM 上。)您的表似乎已去特征化并且您正在使用用户名进行查询。如果用户名改变了怎么办?你会更新 user_images 表吗?
  3. 您的 user_images 表应该有一个 auto_increment 主键,以便您的 order by 可以按 id desc 而非 date 进行排序。您可以在用户名上有一个索引,但这也取决于您的 where 语句的选择性。如果用户名的基数非常低,MySQL 将选择全表扫描。
  4. 您还应该尝试在一个查询(连接)中获取数据,而不是两个。
  5. 您应该使用准备好的语句来保护您免受 SQL 注入。您的代码现在很容易受到攻击。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-12
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多