php—从mysql检索数据以进行本地响应时获取速度慢

z2acfund  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(282)

我不知道是什么原因导致提取如此缓慢。可能是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本机端会快速获取数据。有没有办法在保留所有数据结果的同时加快提取速度?

u0sqgete

u0sqgete1#

在users表的username列上应该有unque索引。这也会让你的假设,只有一行会返回。而且它也会更快,因为mysql会在找到一个记录时返回。
(我没有注意到op在myisam上。)您的表似乎已取消规范化,您正在使用username进行查询。如果用户名变了怎么办?你会更新用户图片表吗?
您的user\u images表应该有一个自动递增的主键,这样您的order by可以是order by id desc,而不是date。您可以在username上有一个索引,但这也取决于where语句的选择性。如果用户名的基数很低,mysql将选择一个完整的表扫描。
您还应该尝试在一个查询(join)中获取数据,而不是在两个查询中。
您应该使用prepared语句来防止sql注入。你的代码现在易受攻击。

相关问题