亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Understanding the Problem: Challenges of Interacting React Route Parameters with PHP Backends
Solution: Use React Hooks useParams to get route parameters
1. Transformation of React front-end components
PHP backend data query (Select by ID)
PHP backend data update (Update by ID)
Things to note and best practices
Summarize
Home Backend Development PHP Tutorial React and PHP backend data interaction: solving routing parameter transfer and ID query and update problems

React and PHP backend data interaction: solving routing parameter transfer and ID query and update problems

Oct 16, 2025 am 11:48 AM

React and PHP backend data interaction: solving routing parameter transfer and ID query and update problems

This article takes an in-depth look at the common routing parameter transfer issues when ID query and update between React front-end and PHP back-end. By analyzing the reasons for the failure of this.props.match?.params.id, the correct use of useParams Hook in React Router v6 is introduced and explained in detail. Combined with the PHP back-end code, it demonstrates how to safely and effectively perform data query and update operations through ID, while emphasizing best practices such as SQL injection protection.

Understanding the Problem: Challenges of Interacting React Route Parameters with PHP Backends

When building modern web applications, data interaction between front-end frameworks (such as React) and back-end services (such as PHP) is core. A common scenario is to query or update a specific resource based on the ID in the URL. However, when developers try to get URL parameters from a React component and pass them to the PHP backend, they may encounter problems where the parameters are undefined or PHP cannot receive the ID.

Specifically, in older versions of React Router (v5 and earlier), components rendered via routes could access URL parameters via this.props.match.params.id. But with the release of React Router v6, this method has been abandoned or no longer directly available. When this property returns undefined, the front end cannot correctly send the ID to the back end, causing $_GET['id'] in the PHP script to fail to obtain the expected value, thus affecting the data query and update operations.

Solution: Use React Hooks useParams to get route parameters

React Router v6 introduces Hooks, which greatly simplifies the acquisition of routing parameters. For functional components, we should use useParams Hook to get dynamic parameters in the URL.

1. Transformation of React front-end components

The original class component needs to be modified, or use useParams through a wrapper. The most recommended way is to refactor class components into functional components to directly utilize Hooks.

Original class component code snippet (problem exists):

 // edit.js (part of the code)
componentDidMount() {
    Axios.get(
        "http://localhost/testing/edit.php?id=" this.props.match?.params.id // This may be undefined
    )
    .then((response) => { /* ... */ })
    .catch(function (error) { console.log(error); });
}

Transform into a functional component and use useParams:

First, make sure your React Router version is v6 or higher.

 // Edit.jsx (functional component)
import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom"; // Import useParams
import Axios from "axios";
import "./Edit.css";
import "react-datepicker/dist/react-datepicker.css";

function Edit() {
    const { id } = useParams(); // Use useParams Hook to obtain routing parameters const [lastName, setLastName] = useState("");
    const [firstName, setFirstName] = useState(""); // Assume firstName is also needed

    useEffect(() => {
        // Get data based on ID when the component is mounted if (id) { // Make sure the id exists Axios.get(`http://localhost/testing/edit.php?id=${id}`)
                .then((response) => {
                    setFirstName(response.data.firstName);
                    setLastName(response.data.lastName);
                })
                .catch((error) => {
                    console.error("Error fetching data:", error);
                });
        }
    }, [id]); // Dependency is id, re-execute when id changes const onChangeLastName = (e) => {
        setLastName(e.target.value);
    };

    const onSubmit = (e) => {
        e.preventDefault();

        const obj = {
            lastName: lastName,
        };

        Axios.post(`http://localhost/testing/update.php?id=${id}`, obj)
            .then((res) => {
                console.log(res.data);
                // You can reset the form or navigation after successful submission // setLastName("");
            })
            .catch((error) => {
                console.error("Error updating data:", error);
            });
    };

    return (
        <div classname="edit">
            <form onsubmit="{onSubmit}">
                <div classname="edit__text">Date & Time Out:</div>
                <label>
                    Last Name:
                    <input name="last" type="text" value="{lastName}" onchange="{onChangeLastName}">
                </label>
                <button type="submit">Submit</button>
            </form>
        </div>
    );
}

export default Edit;

Routing configuration example (App.js):

Make sure you include dynamic parameters in your route paths, for example:

 //App.js
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Edit from "./components/Edit"; // Assume that the Edit component is in the components directory function App() {
    return (
        <router>
            <routes>
                {/* The path contains: id dynamic parameter */}
                <route path="/edit/:id" element="{<Edit"></route>} />
                {/* ... other routes */}
            </routes>
        </router>
    );
}

This way, when accessing /edit/123, useParams() will return { id: "123" }.

PHP backend data query (Select by ID)

The PHP backend is responsible for receiving the ID passed by the frontend and retrieving data from the database accordingly.

edit.php code analysis and optimization:

 <?php require &#39;connect.php&#39;;
// include_once("Core.php"); // If Core.php contains sensitive information or is unnecessary, it can be removed or adjusted as needed // Check whether $_GET[&#39;id&#39;] exists and is not empty, and perform type conversion and cleaning $id = isset($_GET[&#39;id&#39;]) ? (int)$_GET[&#39;id&#39;] : 0; // Use (int) for type conversion to prevent non-numeric input if ($id === 0) {
    http_response_code(400); // Bad Request
    echo json_encode([&#39;error&#39; => 'ID parameter is missing or invalid.']);
    exit;
}

// It is best practice to use prepared statements to prevent SQL injection $sql = "SELECT * FROM `visitors` WHERE `id` = ?";
$stmt = mysqli_prepare($con, $sql);

if ($stmt) {
    mysqli_stmt_bind_param($stmt, "i", $id); // "i" means that the ID is an integer type mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $row = mysqli_fetch_assoc($result);

    if ($row) {
        http_response_code(200); // OK
        echo json_encode($row);
    } else {
        http_response_code(404); // Not Found
        echo json_encode(['error' => 'Visitor not found.']);
    }
    mysqli_stmt_close($stmt);
} else {
    http_response_code(500); // Internal Server Error
    echo json_encode(['error' => 'Database query preparation failed: ' . mysqli_error($con)]);
}

mysqli_close($con); // Close the database connection exit;

?>

Key improvements:

  • Input validation and sanitization : Use isset() and empty() to check $_GET['id'], and use (int) to convert it to an integer to prevent non-numeric input from causing errors or potential security issues.
  • SQL injection protection : Use mysqli_prepare() and mysqli_stmt_bind_param() to create prepared statements. This is the most effective way to prevent SQL injection attacks.
  • HTTP status code : Return the appropriate HTTP status code (200 OK, 400 Bad Request, 404 Not Found, 500 Internal Server Error) according to the operation result to enhance the robustness of the API.
  • Error handling : Add checks on the results of mysqli_prepare() and mysqli_fetch_assoc() and return error information in case of failure.
  • Database connection management : Close the database connection mysqli_close($con) at the end of the script.

PHP backend data update (Update by ID)

Similar to queries, update operations also need to obtain the ID from the URL and obtain the data to be updated from the request body.

update.php code analysis and optimization:

 <?php // include_once("Core.php"); // Same as above require &#39;connect.php&#39;;

// Get the JSON data in the POST request body $postdata = file_get_contents("php://input");

if(isset($postdata) && !empty($postdata)) {
    $request = json_decode($postdata, true); // Add true parameter, decode JSON into associative array // Verify and clean ID parameter $id = isset($_GET[&#39;id&#39;]) ? (int)$_GET[&#39;id&#39;] : 0;
    if ($id === 0) {
        http_response_code(400); // Bad Request
        echo json_encode([&#39;error&#39; => 'ID parameter is missing or invalid.']);
        exit;
    }

    // Verify and clean the data in the request body $lastName = isset($request['lastName']) ? trim($request['lastName']) : '';
    if (empty($lastName)) {
        http_response_code(400); // Bad Request
        echo json_encode(['error' => 'Last name is required.']);
        exit;
    }

    //Use prepared statements to update $sql = "UPDATE `visitors` SET `lastName` = ? WHERE `id` = ? LIMIT 1";
    $stmt = mysqli_prepare($con, $sql);

    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "si", $lastName, $id); // "s" represents a string, "i" represents an integer if (mysqli_stmt_execute($stmt)) {
            if (mysqli_stmt_affected_rows($stmt) > 0) {
                http_response_code(200); // OK
                echo json_encode(['message' => 'Record updated successfully.']);
            } else {
                http_response_code(404); // Not Found (if the ID does not exist)
                echo json_encode(['message' => 'No record found or no changes made.']);
            }
        } else {
            http_response_code(500); // Internal Server Error
            echo json_encode(['error' => 'Database update failed: ' . mysqli_stmt_error($stmt)]);
        }
        mysqli_stmt_close($stmt);
    } else {
        http_response_code(500); // Internal Server Error
        echo json_encode(['error' => 'Database query preparation failed: ' . mysqli_error($con)]);
    }
} else {
    http_response_code(400); // Bad Request
    echo json_encode(['error' => 'No data provided for update.']);
}

mysqli_close($con);
exit;

?>

Key improvements:

  • Data verification and cleaning : Strict verification and cleaning are performed on both $_GET['id'] and $request['lastName'].
  • JSON decoding : json_decode($postdata, true) decodes the JSON string into a PHP associative array for easy access.
  • SQL injection protection : Also use prepared statements for update operations.
  • HTTP status code : Return status code in more detail, such as 200 OK indicating success, 404 Not Found indicating that the ID does not exist or no record has been updated.
  • Error message : Provide more specific error information to help debugging.

Things to note and best practices

  1. React Router version compatibility : Make sure your React Router version is compatible with the API (useParams) used in your code. useParams was introduced in React Router v5.1 and is preferred in v6.
  2. SQL injection protection : This is one of the most important security measures in backend development. Always use Prepared Statements to process all user-entered data and avoid directly splicing SQL query strings.
  3. Error handling and logging : Both the front and back ends should have robust error handling mechanisms. The front end uses try...catch or .catch() to handle API request failures. The back end captures database operation errors and records logs, while returning meaningful error information to the front end.
  4. Standard use of HTTP status codes : Correct use of HTTP status codes can help the front end better understand the back-end response and adopt corresponding processing logic (for example, 404 indicates that the resource does not exist, 400 indicates that the request parameters are incorrect, and 500 indicates an internal server error).
  5. Front-end and back-end data verification : In addition to back-end verification, the front-end can also perform preliminary input verification to improve user experience.
  6. Component structure : Use functional components and Hooks as much as possible, which is the modern development paradigm of React.
  7. API URL management : Configure the basic URL of the API to facilitate switching in different environments (development, testing, production).

Summarize

The key to solving the problem of ID parameter transfer between React front-end and PHP back-end is to understand the API updates brought about by React Router version changes, and use useParams Hook to obtain URL parameters. At the same time, the PHP backend must strictly verify and clean the received parameters, and use prepared statements to perform database operations to ensure the security, stability, and maintainability of the application. By following these best practices, you can build full-stack applications that are efficient, secure, and easy to maintain.

The above is the detailed content of React and PHP backend data interaction: solving routing parameter transfer and ID query and update problems. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

How to check if an email address is valid in PHP? How to check if an email address is valid in PHP? Sep 21, 2025 am 04:07 AM

Usefilter_var()tovalidateemailsyntaxandcheckdnsrr()toverifydomainMXrecords.Example:$email="user@example.com";if(filter_var($email,FILTER_VALIDATE_EMAIL)&&checkdnsrr(explode('@',$email)[1],'MX')){echo"Validanddeliverableemail&qu

MySQL conditional aggregation: Use CASE statement to implement condition summing and counting of fields MySQL conditional aggregation: Use CASE statement to implement condition summing and counting of fields Sep 16, 2025 pm 02:39 PM

This article discusses in depth how to use CASE statements to perform conditional aggregation in MySQL to achieve conditional summation and counting of specific fields. Through a practical subscription system case, it demonstrates how to dynamically calculate the total duration and number of events based on record status (such as "end" and "cancel"), thereby overcoming the limitations of traditional SUM functions that cannot meet the needs of complex conditional aggregation. The tutorial analyzes the application of CASE statements in SUM functions in detail and emphasizes the importance of COALESCE when dealing with the possible NULL values ??of LEFT JOIN.

How to make a deep copy or clone of an object in PHP? How to make a deep copy or clone of an object in PHP? Sep 21, 2025 am 12:30 AM

Useunserialize(serialize($obj))fordeepcopyingwhenalldataisserializable;otherwise,implement__clone()tomanuallyduplicatenestedobjectsandavoidsharedreferences.

How to merge two arrays in PHP? How to merge two arrays in PHP? Sep 21, 2025 am 12:26 AM

Usearray_merge()tocombinearrays,overwritingduplicatestringkeysandreindexingnumerickeys;forsimplerconcatenation,especiallyinPHP5.6 ,usethesplatoperator[...$array1,...$array2].

How to use namespaces in a PHP project? How to use namespaces in a PHP project? Sep 21, 2025 am 01:28 AM

NamespacesinPHPorganizecodeandpreventnamingconflictsbygroupingclasses,interfaces,functions,andconstantsunderaspecificname.2.Defineanamespaceusingthenamespacekeywordatthetopofafile,followedbythenamespacename,suchasApp\Controllers.3.Usetheusekeywordtoi

How to update a record in a database with PHP? How to update a record in a database with PHP? Sep 21, 2025 am 04:47 AM

ToupdateadatabaserecordinPHP,firstconnectusingPDOorMySQLi,thenusepreparedstatementstoexecuteasecureSQLUPDATEquery.Example:$pdo=newPDO("mysql:host=localhost;dbname=your_database",$username,$password);$sql="UPDATEusersSETemail=:emailWHER

What are magic methods in PHP and provide an example of `__call()` and `__get()`. What are magic methods in PHP and provide an example of `__call()` and `__get()`. Sep 20, 2025 am 12:50 AM

The__call()methodistriggeredwhenaninaccessibleorundefinedmethodiscalledonanobject,allowingcustomhandlingbyacceptingthemethodnameandarguments,asshownwhencallingundefinedmethodslikesayHello().2.The__get()methodisinvokedwhenaccessinginaccessibleornon-ex

How to get the file extension in PHP? How to get the file extension in PHP? Sep 20, 2025 am 05:11 AM

Usepathinfo($filename,PATHINFO_EXTENSION)togetthefileextension;itreliablyhandlesmultipledotsandedgecases,returningtheextension(e.g.,"pdf")oranemptystringifnoneexists.

See all articles