原生 PHP,点击提交后表单不断重定向到同一页面

问题描述 投票:0回答:1

我有一个从ajax请求检索ID的实践项目,现在它确实检索具有该ID的书,我已经为要插入数据库的书添加了一个自定义代码,但这里有一个问题

点击提交按钮后,它重定向到与ID相同的页面,但现在不显示书籍的ID和详细信息,

<?php
session_start();

// Check if the User_ID session variable is not set or empty
if (!isset($_SESSION["User_ID"]) || empty($_SESSION["User_ID"])) {
    // Redirect to index.php
    header("Location: ../index.php");
    exit(); // Ensure script execution stops after redirection
}


// Check if the ID parameter is set in the URL
if (isset($_GET['id'])) {
    // Get the ID value from the URL
    $id = $_GET['id'];


    // Database connection
    $conn = mysqli_connect("localhost", "root", "root", "db_library_2", 3308);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    // SQL query to retrieve available books
    $sql = "SELECT tbl_requestbooks.* FROM tbl_requestbooks WHERE Request_ID ='$id'";

    $result = $conn->query($sql);


    echo '<script>console.log("ID RETRIEVED '.$id.'");</script>';
} else {
    // If the ID parameter is not set in the URL
    echo "No ID parameter found in the URL.";
}

if (isset($_POST['submit'])) {
    echo '<script>console.log("Submit Function CLicked");</script>';
    

    $bookTitle = $_POST['Book_Title'];
    $pubname = $_POST['Publisher_Name'];
    $edition = $_POST['tb_edition'];
    $yr = $_POST['Year_Published'];
    $qty = $_POST['Quantity'];
    $price = $_POST['price'];
    $stat = "Pending";
    $country = $_POST['country'];
    $bibliography = "NA";
    $isbn = 1; // Assuming ISBN is always 1
    $sectionCode = $_POST["section"];
    $shelfNumber = $_POST["shelf"];

    $requestID = $_GET['id'];
    $authorsName = $_POST['Authors_ID'];


    // Retrieve the custom Accession Code
    $customAccessionCode = $_POST['accessionCode'];

    // Check if custom Accession Code is provided
    if (!empty($customAccessionCode)) {
        // Use the provided custom Accession Code
        $customAccessionCode = floatval($customAccessionCode);
    } else {
        // Generate a new random 6-digit value
        $randomValue = rand(100000, 999999); // Generate random value between 100000 and 999999
        $customAccessionCode = floatval($randomValue . '.2');
    }


  $checkDuplicateBookSql = "SELECT * FROM tbl_books WHERE Book_Title = '$bookTitle' AND tb_edition = '$edition'";
    $result = $conn->query($checkDuplicateBookSql);

    if ($result->num_rows > 0) {
        // Book already exists, update the quantity
        $row = $result->fetch_assoc();
        $existingQty = $row['Quantity'];
        $newQty = $existingQty + $qty;

        $updateQuantitySql = "UPDATE tbl_books SET Quantity = '$newQty' WHERE Book_Title = '$bookTitle' AND tb_edition = '$edition'";
        if ($conn->query($updateQuantitySql) !== TRUE) {
            echo '<script>console.log("Error updating book quantity: ' . $conn->error . '");</script>';
        }
    } else {
        // Check if the book already exists based on accession code
        $checkDuplicateAccessionCodeSql = "SELECT * FROM tbl_books WHERE Accession_Code = '$customAccessionCode'";
        $result = $conn->query($checkDuplicateAccessionCodeSql);

        if ($result->num_rows > 0) {
            // Accession Code duplicate detected, display message
            echo '<script>alert("Accession Code Duplicate Detected");</script>';
            echo '<script>console.log("Accession Code Duplicate Detected 99");</script>';
   
            // echo '<script>window.location.href = "process_data_book.php?id=' . $id . '";</script>';

       
        } else {
            // Insert the new book into tbl_books
            $booksql = "INSERT INTO tbl_books (Accession_Code ,Book_Title, Authors_ID, Publisher_Name, Section_Code, shelf, tb_edition, Year_Published, ISBN, Bibliography, Quantity, Price, tb_status) 
                        VALUES ('$customAccessionCode','$bookTitle', '$authorsID', '$pubname', '$sectionCode', '$shelfNumber', '$edition', '$yr', '$isbn', '$bibliography', '$qty', '$price', 'Available')";

            if ($conn->query($booksql) !== TRUE) {
                echo '<script>console.log("Error Inserting status 108");</script>';
                // echo '<script>window.location.href = "process_data_book.php?id=' . $id . '";</script>';
            }

            // Update tb_status based on Request_ID
            $updateStatusSql = "UPDATE tbl_requestbooks SET tb_status = 'Approved' WHERE Request_ID = '$requestID'";
            if ($conn->query($updateStatusSql) === TRUE) {
                echo '<script>alert("Record Updated Successfully!");</script>';
                echo '<script>window.location.href = "admin_books.php";</script>';
            } else {
                echo '<script>console.log("Error updating request status: ' . $conn->error . '");</script>';
            }
        }
    }
}


?>

这是首先检查书名和版本是否相同的代码,它会更新与用户输入匹配的记录数量

第二是检查accesion_code是否可用,如果代码不可用则会显示错误,

否则它将插入书籍并更新请求表记录,

这是表格

`

    <div class="mb-3">
            <label for="accessionCode" class="form-label">Custom Accession Code</label>
            <input type="text" class="form-control" id="accessionCode" name="accessionCode">
        </div>`

输出应该是,当我单击提交按钮时,我现在可以在数据库检查后插入新书,但是因为它重定向到带有 iD 的同一页面,所以我无法插入新书

在此输入图片描述

php mysql
1个回答
0
投票

我最终解决了这个问题。我只是简单地利用ajax将数据发送到插入功能所在的其他页面,我可能会弄乱这种形式的代码,利用ajax也是简化和避免页面文件过度拥挤的好方法

© www.soinside.com 2019 - 2024. All rights reserved.