简体   繁体   English

React Native:在 PHP 中更改 mySql 值后更新 Android 中的数据

[英]React Native: Updating Data in Android after changing mySql Value in PHP

I have a simple script to like a Photo.我有一个简单的脚本来喜欢照片。 In Browser everything works fine.在浏览器中一切正常。 Updating data in mySql and showing result in Browser.更新 mySql 中的数据并在浏览器中显示结果。 But in Android when I click "heart" it changes the value in mySql but doesnt show the right result.但是在 Android 中,当我单击“心脏”时,它会更改 mySql 中的值,但没有显示正确的结果。 Pic not liked...click like...mySql showes it was liked...Android doesn show this...click again like...mySql shows pic is not liked...Android showes it was liked Pic not liked...click like...mySql showes it was liked...Android doesn show this...click again like...mySql shows pic is not liked...Android showes it was liked

Here my Code REACT NATIVE:这是我的代码反应原生:

import React from 'react';
import { View, Text, Image, StyleSheet, Dimensions } from 'react-native';

import axios from 'axios';

export default class ImageList extends React.Component {


    constructor(props) {
        super(props);

        this.state = {
            images: [],
            handyWidth: Dimensions.get('window').width,
            mainContainerWidth: Dimensions.get('window').width * 0.96,
            handyHeight: Dimensions.get('window').height,
            imageOptionsWidth: null,
            windowWidth: null,
            windowHeight: null,
            imageWidth: null,
            containerOfPictureMargin: null,
            descriptionMargin: null,
            imageOptionsWidthLeft: null,
            imageOptionsWidthRight: null
        }
    }

    addLike = async (val) => {

        const formData = new FormData();
        formData.append('imageId', val);
        fetch('https://projectwebua.000webhostapp.com/updateLikes.php', {
            body: formData,
            method: 'POST'
        });

        this.loadData();

    };

    loadData = () => {

        axios.get(`https://projectwebua.000webhostapp.com/sqlAnswer.php`)
            .then(res => {
                const images = res.data;
                this.setState({ images });
            })

    }

    componentDidMount() {

        this.state.imageOptionsWidth = this.state.handyWidth;
        this.state.imageWidth = this.state.handyWidth * 0.84;

        this.state.containerOfPicture = this.state.handyWidth * 0.96;
        this.state.containerOfPictureInner = this.state.handyWidth * 0.92;
        this.state.containerOfPictureInnerMargin = this.state.handyWidth * 0.02;

        this.state.descriptionMargin = this.state.handyWidth * 0.03;
        this.state.descriptionTextMargin = this.state.handyWidth * 0.01;
        this.state.descriptionTextMarginHeart = this.state.handyWidth * 0.04;

        this.state.imageOptionsWidthLeft = this.state.handyWidth * 0.7;
        this.state.imageOptionsWidthRight = this.state.handyWidth * 0.22;

        this.state.containerOfPictureMargin = this.state.handyWidth * 0.02;

        this.loadData();

    }

    render() {

        return (
            <View>

                <View>

                    {
                        this.state.images.map((i, k) => (

                            <View>

                                <View style={{

                                    backgroundColor: '#e9f5f9',
                                    marginBottom: 20,
                                    borderColor: "grey",
                                    borderWidth: 1,
                                    width: this.state.containerOfPicture,

                                }}>

                                    <View>

                                        <Image
                                            source={{ uri: i.source }}
                                            style={{ 
                                                width: this.state.containerOfPictureInner, 
                                                height: 200, 
                                                marginLeft: this.state.containerOfPictureInnerMargin, 
                                                marginRight: this.state.containerOfPictureInnerMargin,
                                                marginTop: 10
                                            }}
                                            resizeMode="contain"
                                            resizeMethod="resize"
                                        />

                                    </View>

                                    <View style={{

                                        marginLeft: this.state.descriptionMargin,
                                        marginRight: this.state.descriptionMargin,
                                        borderBottomColor: "grey",
                                        borderBottomWidth: 1,
                                        marginBottom: 10,

                                    }}>

                                        <Text style={{ 
                                            marginLeft: this.state.descriptionTextMargin, 
                                            marginRight: this.state.descriptionTextMargin 
                                        }}>
                                            {i.description}
                                        </Text>

                                    </View>


                                    <View style={{
                                        
                                        flexDirection: 'row',
                                        paddingLeft: 10,
                                        paddingBottom: 10,

                                    }}>

                                        <View style={{
                                            width: this.state.imageOptionsWidthLeft,
                                        }}>
                                            <Text>Likes: {i.likes}</Text>
                                        </View>

                                        <View style={{
                                            width: this.state.imageOptionsWidthRight,
                                            alignItems: 'flex-end',
                                            paddingRight: this.state.descriptionTextMarginHeart
                                        }}>
                                            <Text onPress={() => { this.addLike(i.id) }}>&#129505;</Text>
                                        </View>

                                    </View>

                                </View>

                            </View>

                        ))}

                </View>

            </View >

        )
    }
}

sqlAnswer.php sqlAnswer.php

header('Content-Type: application/json; charset=utf-8');
 header("Access-Control-Allow-Origin: *");
 header("Access-Control-Allow-Methods: PUT, GET, POST");

 $dbhost = "###########";
 $dbuser = "###########";
 $dbpass = "###########";
 $db = "###########";

 $conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n". $conn -> error);
    
 if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
 }

 $sql = "SELECT id, description, likes, source, liked FROM images;";
 $result = mysqli_query($conn, $sql);
 if (!$result) {
    echo 'Query error: ' . mysqli_error($mysqli) . "</br></br>";
    die();
 }
 //ECHO OF DATABASE
 $i=0;
 while ($row = mysqli_fetch_assoc($result)) {
    $response[$i] = array("id" => $row['id'], "description" => $row['description'], "likes" => $row['likes'],  "liked" => $row['liked'], "source" => $row['source']);
    $i++;
 }

 $conn -> close();

 echo json_encode($response);

updateLikes.php updateLikes.php

header('Content-Type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");


console.log('HIER STARTET DB');

$host = "#############";
$user = "#############";
$password = "#############";
$db = "#############";
   
 $conn = mysqli_connect($host, $user, $password,$db);  

 if (!$conn) {
     die("Connection failed: " . mysqli_connect_error());
 }


$sql = "SELECT id, description, likes, source, liked FROM images WHERE id='".$_POST['imageId']."';";


 $result = mysqli_query($conn, $sql);
 if (!$result) {
    echo 'Query error: ' . mysqli_error($mysqli) . "</br></br>";
    die();
 }

 $row = mysqli_fetch_assoc($result);

 if($row['liked'] == "0") {
    
    $insertLiked = "1";
    $insertLikes = $row['likes'] + 1;

    //HERE UPDATE
    
    
 } else {
     
    //Bild wurde schon geliked
    
    $insertLiked = "0";
    $insertLikes = $row['likes'] - 1;
     
 }
 
 $sql = "UPDATE images 
            SET likes = ".$insertLikes.",
                liked = ".$insertLiked." 
        WHERE   id='".$row['id']."';";
 
 mysqli_query($conn, $sql);

fetch is asynchronous function. fetch是异步的 function。 You should wait for it to finish before calling loadData().在调用 loadData() 之前,您应该等待它完成。

await fetch('https://projectwebua.000webhostapp.com/updateLikes.php', {
  body: formData,
  method: 'POST'
});

this.loadData();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM