Results 1 to 12 of 12

Thread: [RESOLVED] How to add my ordering items in a table before saving them in DB

Hybrid View

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    May 2016
    Posts
    157

    Resolved [RESOLVED] How to add my ordering items in a table before saving them in DB

    Hi. I'm new to PHP development. I'm working for my practice on a dummy website. Its kind of sale project.
    Its an ordering Form. Where I have list of items to select from. Once the item is selected, their quantity is entered and their unit price is retrieved and put into textbox. After that there is an Add Item button. I want that when I press the add item button so the selected item is added to the table below. When I finish entering all my items into the table so that table shows me Total amount, and a Button below that for saving the record.
    When I press the save button so all the entries of the table get stored against the Order number.

    When I was working with vb.net so there I had a DataTable, DataSet and Datagrid to work upon. But I don't know that do I have anything similar in PHP.

    Question:
    Do I have any option like dataTable or Dataset in PHP. Where I could add items like this?

    If my delivered idea is not clear so I can explain more?

  2. #2
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,711

    Re: How to add my ordering items in a table before saving them in DB

    I wouldn't use PHP for you front-end operations. What I would be doing is the following:
    1. Use JavaScript to make an AJAX get request to a PHP endpoint that returns every item you want to display in a JSON array
    2. Once you have the data, use JavaScript to iterate over the collection to create the DOM representation
    3. When the user clicks on the add item button, use JavaScript to push that item, along with the quantity, to an array that is persisted in localstorage
    4. When the user is finished adding items and they want to save their list, use JavaScript to make an AJAX post request to a PHP endpoint that takes the item array


    Are you comfortable separating the front-end from the back-end like that?
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    May 2016
    Posts
    157

    Re: How to add my ordering items in a table before saving them in DB

    Hmmmm. For my front-end I had no idea what to do. So after searching and asking and now you hit the target. I started learning jQuery instead of JS. Because everyone said in tutorials that JS was much complex than jQuery. So I followed and following a tutorial where fundamental jQ is taught. I thought that it would help. But at the end of tutorial it did not do what I was looking for.

    Then I found an AJAX tutorial where the guy is working on something I need.

    @dday, Sir I did not understand few things in your post but some of them and I got a little idea.

    What I know right now sir is that I have some of understanding of jQ and some of its events. and now I've started AJAX from a couple of tutorial, they are not teaching that what is actually happening in their videos.

    Guide me that am I going right way?

  4. #4
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,711

    Re: How to add my ordering items in a table before saving them in DB

    To clarify, jQuery is a JavaScript library. When you're executing jQuery code, it is ultimately running JavaScript, just using a more flavorful syntax. I personally enjoy working with both, but I would suggest learning JavaScript before learning jQuery.

    In terms of step 1 (Use JavaScript to make an AJAX get request to a PHP endpoint that returns every item you want to display in a JSON array), imagine you have the following PHP code:
    PHP Code:
    <?php
        http_response_code
    (200);

        
    $products = array(
            array(
    "ProductId" => 1"ProductName" => "Widget1""Cost" => "5.00"),
            array(
    "ProductId" => 2"ProductName" => "Widget2""Cost" => "3.50"),
            array(
    "ProductId" => 3"ProductName" => "Widget3""Cost" => "3.00"),
            
    // etc...
        
    );

        echo 
    json_encode($products);
    ?>
    Then you could submit an AJAX GET request by using the following JavaScript code:
    Code:
    window.onload = function() {
        const request = new XMLHttpRequest();
        request.onreadystatechange = function() { 
            if (request.readyState == 4 && request.status == 200) {
                 const products = request.responseJSON;
                 // TODO: setup step 2
            }
        }
    }
    
    request.open('GET', 'my-php-file.php', true );            
    request.send(null);
    At this point, upon a successful request, your products will be stored in the variable products. You will see that I have a comment just afterwards reserved for step 2.

    Now that you have the products, you should iterate over the array and create your DOM.

    The DOM can be something simple like this:
    HTML Code:
    <ol>
      <li><a href="#" data-productId="[id]">[name] - $[cost]</a></li>
      <!-- etc... -->
    </ol>
    What you could do is setup a function to create the DOM, then call that function where the comment is. The function could be like the following:
    Code:
    const buildProductsList = function(products) {
        products = products || [];
    
        const orderedList = document.createElement('ol');
        for (const key in products) {
            if (Object.prototype.hasOwnProperty.call(products, key)) {
                const product = products[key];
                const listItem = document.createElement('li');
                listItem.innerHTML = `${product.ProductName} - ${product.Cost}`;
                listItem.dataset.productId = product.ProductId;
                orderedList.appendChild(listItem);
            }
        }
    
        return orderedList;
    }
    Now your total code would look like this:
    Code:
    window.onload = function() {
        const request = new XMLHttpRequest();
        request.onreadystatechange = function() { 
            if (request.readyState == 4 && request.status == 200) {
                 const products = request.responseJSON;
                 const orderedList = buildProductsList(products);
            }
        }
    }
    
    const buildProductsList = function(products) {
        products = products || [];
    
        const orderedList = document.createElement('ol');
        for (const key in products) {
            if (Object.prototype.hasOwnProperty.call(products, key)) {
                const product = products[key];
                const listItem = document.createElement('li');
                const anchor = document.createElement('a');
                a.innerHTML = `${product.ProductName} - ${product.Cost}`;
                a.dataset.productId = product.ProductId;
                listItem.appendChild(anchor)
                orderedList.appendChild(listItem);
            }
        }
    
        return orderedList;
    }
    Now that the DOM is being build dynamically, you will need to bind the event handler (step 3).

    I can help out more later, but for now I need to head home.

    Update
    I'm home now, so I can finish. I've also updated the method to create an anchor.

    Inside of the for/in loop, you need to setup the event handler for the anchor which can be done by using addEventListener method. For now we will setup a simple function that calls console.log to be used as a placeholder for the second part of step 3:
    Code:
    const buildProductsList = function(products) {
        products = products || [];
    
        const orderedList = document.createElement('ol');
        for (const key in products) {
            if (Object.prototype.hasOwnProperty.call(products, key)) {
                const product = products[key];
                const listItem = document.createElement('li');
                const anchor = document.createElement('a');
                anchor.innerHTML = `${product.ProductName} - ${product.Cost}`;
                anchor.dataset.productId = product.ProductId;
                listItem.appendChild(anchor)
                orderedList.appendChild(listItem);
                document.addEventListener('click', (e) => {
                    console.log(e.target.dataset.productId);
                });
            }
        }
    
        return orderedList;
    }
    Now that the ordered list is created, each individual list item is created, each individual anchor is created, and now the anchor's click event has been bound we can prompt the user for the quantity. This can be done by using the prompt method. Once you have the quantity you can push it along with the id to local storage:
    Code:
    document.addEventListener('click', (e) => {
        const productId = e.target.dataset.productId;
        const quantity = prompt('Quantity:');
        const cart = localStorage.getItem('cart') || [];
        cart.push({
            ProductId: productId,
            Quantity: quantity
        });
        localStorage.setItem('cart', cart);
    });
    The final piece to this is when the user goes to "checkout". At that point, you would get the cart from the localstorage, and send it to your endpoint. I can't really help with this without seeing how you plan on handling the incoming data.

    Now all of this uses incredibly simple CSS and JavaScript. You can make it pretty by styling everything, adding a bit more business logic, but hopefully this gives you an idea of how the process would work.
    Last edited by dday9; May 3rd, 2021 at 10:19 PM.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    May 2016
    Posts
    157

    Re: How to add my ordering items in a table before saving them in DB

    @dday.
    After following the AJAX tutorial, I learned some basic CRUD operation using AJAX.
    This is my HTML code insertdata.php
    HTML Code:
    <body>
        <table id="main" border="1px" cellspacing="0">
            <tr>
                <td id="header">
                    <h1>PHP with AJAX</h1>
                </td>
            </tr>
            <tr>
                <td id="table-form">
                <form id="addform">
                    Student First Name: <input type="text" id="st-first-name">&nbsp;
                    Student Last Name: <input type="text" id="st-last-name">
                    <select id="lstName">
                    </select>
    
                    <input type="submit" value="Save Data" id="save-data"><br>
                </form>
                
                </td>
            </tr>
            <tr>
                <td id="table-data">
                    <table border="1px" width="100" cellspacing="0px" cellpadding="10px">
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                        </tr>
                        <tr>
                            <td align="center">1</td>
                            <td>Abid Durrani </td>
                        </tr>                          
                    </table>
                </td>
            </tr>
        </table>
    This is my AJAX code on the same page.
    Code:
    $("document").ready(function(){
                function loadData(){
                    $.ajax({
                        url: "ajaxload.php",
                        type: "post", 
                        success: function(data){
                                                    
                            $("#table-data").html(data);
                            //$("#lstName").html(data1);
                        }        
                    }); 
                } });
    And this is my PHP code to load the data: ajaxload.php
    PHP Code:
    <?php

    $myConn 
    mysqli_connect("localhost""root""""test") or die("Your Connection Failed");
    $sqlQuery "select * from students";
    $result mysqli_query($myConn$sqlQuery) or die ("Your Query Execution Failed");
    $output "";
    $output1 "";

    if(
    mysqli_num_rows($result) > 0) {
        
    $output "
                <table border='2' cellpadding='5px' cellspacing='5px'>
                <tr>
                    <th width='100px'>ID</th>
                    <th>Name</th>
                    <th width='100px'>Delete</th>
                </tr>"
    ;

                while(
    $row mysqli_fetch_assoc($result)){
                    
    $output .= "    
                    <tr>
                        <td>
    {$row['st_id']}</td>
                        <td>
    {$row['st_first_name']}</td>
                        <td><button class='btn-delete' data-myid=
    {$row['st_id']}>Delete</button></td>
                    </tr>"
    ;            
            }
                
    $output .= "</table>";             

            
    mysqli_close($myConn);        
            echo 
    $output;
    } else
    {
        echo 
    "sorry, no record found";
    }
    ?>
    In this my practice, a table is created in ajaxload.php and then it is echoed to success function where it is finally displayed in the Table element in insertdata.php.
    Question:
    1. How to display mySQL data into different HTML elements except Table? For example in this code data is displayed only in HTML table by using AJAX. I've also created a SELECT
    HTML Code:
    <select id="lstName"></select>
    element where I also want to show student First Name only.
    2. For this purpose, do I need to echo another variable from ajaxload.php?

  6. #6
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,711

    Re: How to add my ordering items in a table before saving them in DB

    In this my practice, a table is created in ajaxload.php and then it is echoed to success function where it is finally displayed in the Table element in insertdata.php.
    Do not do that! What winds up happening is you pigeon hole yourself to using the DOM that's been created in the server. Instead, return the data you want to display, formatted to a JSON array and build the DOM on the fly using JavaScript/jQuery. This will solve your issue with both of your questions.

    Also, do not use mysqli_query. PHP has a better way to communicate with MySQL through PDO (documentation).

    Take a look at this example using your schema:
    PHP Code:
    <?php

    $sql 
    'SELECT * FROM students;';
    $connection = new PDO('mysql:host=localhost;dbname=test''root''');
    $statement $connection->prepare($sql);

    $statement->execute();

    $rowCount 0;

    $result = array();
    $result['records'] = array();
    while (
    $row $statement->fetch(PDO::FETCH_ASSOC)) {
        
    $rowCount++;

        
    $record = array(
            
    'id' => $row['st_id'],
            
    'firstName' => $row['st_first_name'],
            
    'lastName' => $row['st_last_name'],
        );

        
    array_push($result['records'], $record);
    }

    $result['total'] = $rowCount;

    http_response_code(200);
    echo 
    json_encode($result);
    ?>
    This will produce a JSON object that looks like this:
    Code:
    {
        "total": 1,
        "records": [
            {
                "id": 1,
                "firstName": "Joe",
                "lastName": "Burreaux"
            }
        ]
    }
    This means that when you get a successful AJAX response, you can build your DOM on the front-end using the relevant information.

    Update
    Take a look at this example that builds a table on the fly based on the JSON response I showed above:
    Code:
    const buildTable = function(students) {
      const columnTitles = [
        {
          field: 'id',
          title: 'Id'
        },
        {
          field: 'firstName',
          title: 'First Name'
        },
        {
          field: '',
          title: 'Delete'
        }
      ];
    
      // build the table
      const table = document.createElement('table');
      table.setAttribute('border', '2');
      table.setAttribute('cellpadding', '5px');
      table.setAttribute('cellspacing', '5px');
    
      // build the table head
      const tableHead = document.createElement('thead');
      const tableHeadRow = document.createElement('tr');
      for (const columnTitle in columnTitles) {
        const tableHeadCell = document.createElement('th');
        tableHeadCell.innerHTML = columnTitles[columnTitle].title;
        tableHeadRow.appendChild(tableHeadCell);
      }
      tableHead.appendChild(tableHeadRow);
      table.appendChild(tableHead);
    
      // build the table body
      const tableBody = document.createElement('tbody');
      if (!students || !students.records) {
        // prematurely return the DOM if there aren't any records
        const blankRow = document.createElement('tr');
        const blankCell = document.createElement('td');
        blankCell.setAttribute('colspan', columnTitles.length.toString());
        blankCell.innerHTML = 'No records returned';
        blankRow.appendChild(blankCell);
        tableBody.appendChild(blankRow);
        table.appendChild(tableBody);
    
        return table;
      }
    
      for (const row in students.records) {
        const tableBodyRow = document.createElement('tr');
        for (const columnTitle in columnTitles) {
          const tableBodyCell = document.createElement('td');
          if (columnTitle < columnTitles.length - 1) {
            tableBodyCell.innerHTML = students.records[row][columnTitles[columnTitle].field];
          } else {
            const button = document.createElement('button');
            button.dataset.id = students.records[row].id;
            button.innerHTML = 'Delete';
            tableBodyCell.appendChild(button);
          }
          tableBodyRow.appendChild(tableBodyCell);
        }
        tableBody.appendChild(tableBodyRow);
      }
      table.appendChild(tableBody);
    
      return table;
    }
    Fiddle: https://jsfiddle.net/cmer29op/
    Last edited by dday9; May 15th, 2021 at 11:35 AM.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    May 2016
    Posts
    157

    Re: How to add my ordering items in a table before saving them in DB

    Thank you soooo much dday that you've given this much time.

    Sir, sir sir, PHP OOP and JSON are ahead of me. I've not touched it yet. As I'm every new to PHP and very very very new to jQuery. These are right now out of my circle.
    I'm so sorry, but I think you want to tell me here
    Do not do that! What winds up happening is you pigeon hole yourself to using the DOM that's been created in the server.
    that why are you creating Table in PHP? Right Sir?

    Second, not a single line of code is known/ familiar to me as I've not been through JS and PHP OOP at all.

    Right now, I want to say that how to solve my problem?
    Second, if JSON is that much important then give me an easiest path to follow on. I've discussed with my friends, they say that JSON and APIs are step ahead and advance, particularly for smartphones. So restrict yourself for the time being till jQuery. Once you get a good practice of your basics then go to further advancements.

    Guide me please

  8. #8
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,711

    Re: How to add my ordering items in a table before saving them in DB

    As I stated in post #4, I would highly recommend that you learn vanilla JavaScript before learning a JavaScript library like jQuery.

    JSON is an incredibly simple way to express data. Not only is it easy for humans to read JSON, but machines can parse it very easily. JSON has essentially 6 data types:
    • Object
    • Array
    • String
    • Number
    • Boolean
    • Null


    Since you're familiar with Visual Basic .NET, consider this class:
    Code:
    Public Class Student
        Public Property id As Integer
        Public Property firstName As String
        Public Property lastName As String
    End Class
    
    Dim student1 = New Student() With { .id = 1, .firstName = "Joe", .lastName = "Burreaux" }
    This is expressed in JSON as an object:
    Code:
    {
        "id": 1,
        "firstName": "Joe",
        "lastName": "Burreaux"
    }
    Strings are represented as Unicode text surrounded by double-quotes, e.g.:
    Code:
    "this is a string"
    Numbers are represented as a number with an optional unary negative sign, optional fraction, and optional exponent, e.g.:
    Code:
    1
    -1.0
    123.45e+678
    Booleans are represented as true/false values, e.g.:
    Code:
    true
    false
    Nulls are represented as null, e.g.:
    Code:
    null
    Arrays represent a collection of JSON values. The values do not need to be of the same type, i.e. you can have a String at index 0 and an Object at index 1. Arrays surround their values with square brackets, e.g.:
    Code:
    [
        "Item 1",
        2,
        true,
        null,
        { "key": "value" }
    ]
    that why are you creating Table in PHP? Right Sir?
    I am absolutely not creating the table in PHP. All the PHP does is query the MySQL database and return the data. It is the JavaScript that is actually building the DOM for the table.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  9. #9

    Thread Starter
    Addicted Member
    Join Date
    May 2016
    Posts
    157

    Re: How to add my ordering items in a table before saving them in DB

    That seems interesting.
    Well, do you suggest any source of learning for absolute beginners?

    Secondly, I've heard that things you can do in JS can be accomplished more easily in jQuery. That is why I preferred jQuery instead of JS. The thing you want me to do, can't I do the same in jQuery?

  10. #10
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,711

    Re: How to add my ordering items in a table before saving them in DB

    I would suggest w3schools: https://www.w3schools.com/

    This is where I personally learned HTML, CSS, JavaScript, and jQuery.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  11. #11

    Thread Starter
    Addicted Member
    Join Date
    May 2016
    Posts
    157

    Re: How to add my ordering items in a table before saving them in DB

    @dday9

    I've somehow learned some of the json and worked like this:
    On my index.php page I"ve made this:
    Code:
    $.getJSON(
                "fetch-json-data.php", 
                function(data){
                    console.log(data);
                    $.each(data, function(key, value){
                        //$("#fetch-json").append(value.st_id + " " + value.st_first_name + "<br>");
                        $("#titles").append("<option>" + value.st_id + "</option>");
                    });
                    
                }
            );
    and on my fetch-json-data.php, I coded this:
    Code:
    $conn = mysqli_connect("localhost", "root", "", "test") or die ("Your Connection Failed");
    
    $sql = "Select * from students";
    $Query = mysqli_query($conn, $sql);
    $output = mysqli_fetch_all($Query, MYSQLI_ASSOC); //It transform the array into associative one. mysqli_asssoc, num, both
    
    
    echo json_encode($output); // This functino will convert the array into JSON data/ format
    Perhaps you wanted me to do the same thing, or I grabbed some of your thoughts and did this.
    Question:
    1. Is it ok sir to work like this?

    Thanks

  12. #12
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,711

    Re: How to add my ordering items in a table before saving them in DB

    Yeah, if that works for you then that's fine. I would still highly suggest using PHP's PDO instead of mysqli, but that's up to you.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width