-2

I am looking to insert the eqiup_type and equip instead of their id numbers to the database. If I change the id from this code: <option value="<?php echo $row['id']; ?>"><?php echo $row['equip_type']; ?></option> it will break the drop down menu but when I put it on the other drop down it does not break. So I this time equip will insert its name but not equip_type. How do I get equip_type to be inserted by its name not it's id?

Index.php:

<?php
include_once("db.php");
include_once("response.php");
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, inital-scale=1.0">
        <title>Saftey CheckList</title>
        <link href="main.css" rel="stylesheet">

        <!-- jquery cdn -->
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script src="jquery.min.js"></script>

        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script src="jquery-3.2.1.min.js"></script>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script src="ajax-jquery.min.js"></script>
    </head>

    <body>
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-md-8">
                    <div class="card mt-5">
                        <div class="card-header">
                            <h4>Saftey Checks</h4>
                        <div class="card-body">
                        
                            <form action="combine.php" method="POST">

                            <div class="form-group">
        <?php 
            date_default_timezone_set("US/Central");
        ?>

            <label for="datetime">Selected Date and Time:</label>
            <input type="datetime-local" name="date" id="datetime" value="<?php echo date('Y-m-d\TH:i'); ?>" readonly>
        </div>

                                <div class="form-group">
                                    <?php 

                                        date_default_timezone_set("US/Central");

                                        $start = "18:00:00";
                                        $end = "00:00:00";
                                        $now = date("H:i:s");
                                        $date = date_create("now");

                                        if($now >= $start || $now <= $end){
                                        echo ('3');
                                        }
                                        else
                                        echo ('1');

                                    ?>
                                </div>

                                <div class="form-group">
                                    <div class="row">
                                        <div class="col-lg-6">
                                            <div class="form-group">
                                                <label>User Id</label>
                                                <input type='text' name="user_id"
                                                    id='user_id' class='form-control'
                                                    placeholder='Enter user id'
                                                    onkeyup="GetDetail(this.value)" value="">
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <div class="row">
                                        <div class="col-lg-6">
                                            <div class="form-group">
                                                <label>First Name:</label>
                                                <input type="text" name="first_name"
                                                    id="first_name" class="form-control"
                                                    placeholder='First Name'
                                                    value="">
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="form-group">
                                <label for="country"> Country</label>
                                <select class="form-select" name="equip_type" id="country">
                                    <option value=""> Select Country</option>
                                    <?php

                                    $query = "select * from EquipmentType";
                                    // $query = mysqli_query($con, $qr);
                                    $result = $con->query($query);
                                    if ($result->num_rows > 0) {
                                        while ($row = mysqli_fetch_assoc($result)) {

                                    ?>
                                            <option value="<?php echo $row['id']; ?>"><?php echo $row['equip_type']; ?></option>
                                    <?php
                                        }
                                    }

                                    ?>
                                    </select>
                                </div>

                                <br>

                                <div class="form-group">
                                    <label for="country"> State</label>
                                    <select class="form-select" name="equip" id="state">
                                        <option value="">select State</option>
                                    </select>
                                </div>

                                <div class="form-group">
                                    <input type="checkbox" name="confirm" class="form-control"/> Confirm
                                </div>
                                
                                <div class="form-group">
                                    <lable>Work Order</label>
                                    <input type="text" name="work_order" class="form-control"/>
                                </div>

                                <div class="form-group">
                                    <lable>Notes</label>
                                    <input type="text" name="notes" class="form-control"/>
                                </div>

                                <div class="form-group">
                                    <input type="checkbox" name="S/D" class="form-control"/> S/D
                                </div>

                                <div class="form-group">
                                    <button type="submit" name="save_checkbox" class="btn btn-primary"> Save Data </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="container">
        <div class="row">
            <div class="col-md-12 pt-4">
                <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1190033123418031" crossorigin="anonymous"></script>
                <!-- live_demo_page -->
                <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-1190033123418031" data-ad-slot="5335471635" data-ad-format="auto" data-full-width-responsive="true"></ins>
                <script>
                    (adsbygoogle = window.adsbygoogle || []).push({});
                </script>
            </div>
        </div>
    </div>


    <script>
        $(document).ready(function() {
            $("#country").on('change', function() {
                var countryid = $(this).val();

                $.ajax({
                    method: "POST",
                    url: "response.php",
                    data: {
                        id: countryid
                    },
                    datatype: "html",
                    success: function(data) {
                        $("#state").html(data);
                    }
                });
            });
        });
    </script>

<script>

// onkeyup event will occur when the user
// release the key and calls the function
// assigned to this event
function GetDetail(str) {
    if (str.length == 0) {
        document.getElementById("first_name").value = "";
        return;
    }
    else {

        // Creates a new XMLHttpRequest object
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {

            // Defines a function to be called when
            // the readyState property changes
            if (this.readyState == 4 &&
                    this.status == 200) {
                
                // Typical action to be performed
                // when the document is ready
                var myObj = JSON.parse(this.responseText);

                // Returns the response data as a
                // string and store this array in
                // a variable assign the value
                // received to first name input field
                
                document.getElementById
                    ("first_name").value = myObj[0];
                
              
            }
        };

        // xhttp.open("GET", "filename", true);
        xmlhttp.open("GET", "gfg.php?user_id=" + str, true);
        
        // Sends the request to the server
        xmlhttp.send();
    }
}
</script>

        <script src="https://code.jquery.com/jquery-3.5.1js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js"></script>
    </body>
</html>

response.php:

<?php
include_once("db.php");
if (!empty($_POST["id"])) {
    $id = $_POST['id'];
    $query = "select * from equipment where equip_id=$id";
    $result = mysqli_query($con, $query);
    if ($result->num_rows > 0) {
        echo '<option value="">Select State</option>';
        while ($row = mysqli_fetch_assoc($result)) {
            echo '<option value="' . $row['equip'] . '">' . $row['equip'] . '</option>';
        }
    }
}

combine.php:

<?php
//error reporting remove at the end 
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
// Use more secure database connection methods and consider using environment variables for credentials
$con = new mysqli("localhost", "root", "root", "safetycheck");

if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
}

if (isset($_POST['save_checkbox'])) {
    // Check if 'S/D' key exists in the $_POST array
    if (isset($_POST['S/D'])) {
        $SD = $_POST['S/D'];
    } else {
        $SD = 'off'; // Set to null if 'S/D' checkbox is not checked
    }
    // Use prepared statements and parameter binding
    $stmt = $con->prepare("INSERT INTO `demo` (user_id, first_name, confirm, equip_type, equip, work_order, notes, `S/D`, date_column, value_column) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssssssss", $_POST['user_id'], $_POST['first_name'], $_POST['confirm'], $_POST['equip_type'], $_POST['equip'], $_POST['work_order'], $_POST['notes'], $SD, $adjustedDate, $valueToInsert);

    $adjustedDate = ""; // Initialize variables
    $valueToInsert = 0;

    date_default_timezone_set("US/Central");
    $selectedDateTime = new DateTime($_POST['date']);
    $adjustedDate = $selectedDateTime->format('Y-m-d H:i:s');

    $startRange = new DateTime($selectedDateTime->format('Y-m-d') . " 00:00:00");
    $endRange = new DateTime($selectedDateTime->format('Y-m-d') . " 06:00:00");

    if ($selectedDateTime >= $startRange && $selectedDateTime <= $endRange) {
        $adjustedDate = $selectedDateTime->modify('-1 day')->format('Y-m-d H:i:s');
    }

    $startValueRange = new DateTime($selectedDateTime->format('Y-m-d') . " 18:00:00");
    $endValueRange = new DateTime($selectedDateTime->format('Y-m-d') . " 00:00:00");

    if ($selectedDateTime >= $startValueRange && $selectedDateTime <= $endValueRange) {
        $valueToInsert = 3;
    } else {
        $valueToInsert = 1;
    }

    if ($stmt->execute()) {
        // Redirect back to index.php
        header("Location: index.php");
        exit(); // Make sure to exit to prevent further code execution
    } else {
        echo "Error: " . $stmt->error;
    }
    $stmt->close();
}

$con->close();
?>

I need both equip and equip_type to be inserted by it name not by their id numbers. I have swap the id with the name but it will break the drop down menu. I am using jquery to make the drop down and this could be the reason why it not working but not for sure.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 2
    Why would you need to insert the ID _and_ the name? That would lead to a denormalised data structure with duplication. There should be no good reason to do that. If you need to know the name of the ID you inserted, do a SELECT query on the demo table which JOINs back to the equipment table – ADyson Aug 08 '23 at 21:22
  • 3
    A foreign key should usually refer to the primary key of the referenced table, so putting `equip_id` in the `demo` table is the right thing to do. – Barmar Aug 08 '23 at 21:22
  • Why do you have `name="equip"` on the `State` dropdown? – Barmar Aug 08 '23 at 21:23
  • 2
    Your sql query in response.php is vulnerable to sql injection. Prepare and parameterise it properly like the INSERT – ADyson Aug 08 '23 at 21:24
  • I need to have it this way due to the database being linked to MS Access database and due to that I can not mess with that table structure. – dylan glaser Aug 08 '23 at 21:28
  • 2
    Being linked to Access doesn't stop you having proper foreign key relationships! – ADyson Aug 08 '23 at 21:31
  • 3
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Aug 08 '23 at 21:32
  • Anyway, if you really want to make this mistake, just put the name into the `value` of each `option` and that is what will be posted back to the server. – ADyson Aug 08 '23 at 21:32
  • The way it going to be setup is by having both MySQL and Access share the same table at the same time. I am just taking all their table and linking it back and forth so it will need the same name and id. I could be mistaken by this. I will give the JOIN table a try to see if it works. – dylan glaser Aug 08 '23 at 21:36
  • 2
    Yeah I don't see how linking the tables in Access would be preventing you having a better table design. Access can use JOIN queries too – ADyson Aug 08 '23 at 21:37
  • I have no control over how the access database is setup and I do not know enough on MySQL database to fix the issue while not messing up the access database. If access does not care about it being a key id number than the name than yes it will be a lot better. That's why I ask this question on it. – dylan glaser Aug 08 '23 at 21:46
  • 2
    I'm sorry, but I agree with Barmar and ADyson: ms access is also a relational database, so linking mysql tables there should not compromise applying basic relational database design concepts in mysql! In ms access you can configure even tables to lookup foreign key values from other tables. – Shadow Aug 08 '23 at 22:27
  • You may need to negotiate with the person who controls the Access database and get them to understand the problem and adjust their design a bit as well. – ADyson Aug 09 '23 at 08:08

0 Answers0