Updating a null value within the database was done successfully

Currently, I am working with angular CLI version 8.1.0 and have a user list displayed on a mat table. Upon clicking on a specific user, a new page opens up containing two buttons - "approve" and "reject". The issue I am facing is that when I click on "approve", the column should update from "pending" to "approve" for that particular user. However, instead of updating the column with the value "approve", it is being updated with an empty value. Could someone please assist me with this problem?

index.php

<?php

    $conn=mysqli_connect("localhost","root","root","angdb");

    $request=$_SERVER['REQUEST_METHOD'];

    $data=array();
    switch($request)
    {
        case 'GET':
            response(getData());
            break;

        case 'PUT':
            response(updateData());

        default:
            #code...
            break;
    }

    function getData()
    {
        global $conn;

        if(@$_GET['id'])
        {
            @$id=$_GET['id'];

            $where="AND id=".$id;
        }
        else
        {
            $id=0;
            $where="";
        }


        $query=mysqli_query($conn,"select * from vendor where status='pending' ".$where);
        while($row=mysqli_fetch_assoc($query))
        {
            $data[]=array("id"=>$row['id'],"changeColumn"=>$row['changeColumn'],"type"=>$row['type'],"timestamp"=>$row['timestamp'],"status"=>$row['status'],"name"=>$row['name']);
        }
        return $data;
    }

    function updateData()
    {
        global $conn;
        parse_str(file_get_contents('php://input'),$_PUT);

        if(@$_GET['id'])
        {
            @$id=$_GET['id'];

            $where="where id=".$id;
        }
        else
        {
            $id=0;
            $where="";
        }

        $query=mysqli_query($conn,"update vendor set status='".$_PUT['status']."'".$where);

        if($query==true)
        {
            $data[]=array("Message"=>"Updated");
        }
        else
        {
            $data[]=array("Message"=>"Not updated");
        }
        return $data;
    }

    function response($data)
    {
        echo json_encode($data);
    }
?>

api.service.ts

updateById(id,payload)
{
   let url = `http://localhost/angular_admin/php/index.php?id=${id}`
   return this.httpClient.put(url, payload);
}

approval.component.ts

approve() {
    this.apiService.updateById(this.id, {status:'approve'})
    .subscribe((data:any)=> {
        if (data.Message == "Updated") { // check if the result is sucess then navigat to
            this.router.navigate(["/home/vendor-action"]);
        }
    });
}

Answer №1

To ensure proper data retrieval in your PHP file, it is recommended to utilize the GET method within your query as it aligns with how browsers interact.

function updateData()
{
    global $conn;
    parse_str(file_get_contents('php://input'),$_PUT);

    if(@$_GET['id'])
    {
        @$id=$_GET['id'];

        $where="where id=".$id;
    }
    else
    {
        $id=0;
        $where="";
    }

    $query=mysqli_query($conn,"update vendor set status='".$_GET['status']."'".$where);

    if($query==true)
    {
        $data[]=array("Message"=>"Updated");
    }
    else
    {
        $data[]=array("Message"=>"Not updated");
    }
    return $data;
}

Answer №2

I completely agree that enhancing the design is crucial and it's important to pinpoint a specific problem. Without clear identification, troubleshooting becomes challenging.

Feel free to test the provided code below and let us know if the issue persists. I've included console log and echo statements for testing purposes, which can be removed later on.

approval.component.ts

approve() {
    this.apiService.updateById({id: this.id, status:'approve'})
    .subscribe((data:any)=> {
      console.log('data loaded successfully');
        if (data.Message == "Updated") { // check if the result is sucess then navigat to
            this.router.navigate(["/home/vendor-action"]);
        }
    }, (error) => {
      console.log(error);
    });
}

api.service.ts

updateById(payload)
{
   let url = `http://localhost/angular_admin/php/index.php?id=${id}`
   return this.httpClient.put(payload);
}


index.php

function updateData()
    {
        global $conn;
        parse_str(file_get_contents('php://input'),$_PUT);
        
        $status = $_PUT['status'];
        $id = $_PUT['id'];
        
        $sql = "UPDATE vendor SET status=".$status." WHERE id=".$id.";
           
        $query=mysqli_query($conn, sql);
        $data = array();

        if($query==true)
        {
            $data[]=array("Message"=>"Updated");
        }
        else
        {
            $data[]=array("Message"=>"Not updated");
        }
        return $data;
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to customize the open/close icon on a PrimeNG Panel?

Looking to customize the open/close icon on the Angular PrimeNG panel component. At the moment, it's displaying a plus/minus sign, but I'd like to switch it out for a chevron up/chevron down icon instead. While I've managed to add extra icon ...

Why does the private map function in the class fail while the global function succeeds?

Issues arise when calling the map() function on a parsed JSON object within the mapStocks() function. Placing the toStock() function inside the StockService class results in failure, whereas declaring it as a "global" function outside the class works witho ...

Setting a callback function as a prop for react-paginate in TypeScript: A step-by-step guide

When using react-paginate, there is a prop called onPageChange with the following type: onPageChange?(selectedItem: { selected: number }): void; After implementing it like this: const onPageChange = (selected): void => { console.log(selected); } ...

Creating Dynamic HTML/DOM in Angular 14: A Guide for Adding New Items to a List

I am currently iterating through a list of items and displaying them within a div element. These items are rendered when the page initially loads. <button (click)="addCut()" mat-raised-button color="primary">Add New Cut</button ...

Encountering an issue with extending the MUI color palette, receiving a "reading 'dark'" error due to properties of undefined

Encountering an issue when trying to expand the MUI color palette—getting this error instead: Error: Cannot read properties of undefined (reading 'dark') Take a look at my theme.ts file below: const theme = createTheme({ palette: { pri ...

Retrieving an array of objects from an API and attempting to store it using useState, but only receiving an empty

I have been working on fetching data from an API, storing it in Redux store initially, and then attempting to retrieve it using useSlector to finally save it in local state. Despite getting the data when I console.log it, I am unable to successfully store ...

Executing a method during the initialization process in app.component.ts

One thing I've noticed is that the <app-root> component in Angular doesn't implement OnInit like all the other components. It may sound silly, but let's say I wanted to add a simple console.log('Hello World') statement to dis ...

Creating a custom Higher Order Component to seamlessly connect react-relay and react-router using TypeScript

Hey there! So, my Frankenstein monster project has decided to go rogue and I'm running out of hair to pull out. Any help would be greatly appreciated. I've been working on setting up a simple app with React, React-Router, React-Relay, and Typesc ...

What steps can I take to troubleshoot and resolve the error occurring during the construction of my Angular application?

I encountered an error with the sass-loader while developing my Angular application. Despite attempting to update the sass-loader dependency, I was unable to resolve the issue. Can anyone offer assistance? Here is all the relevant information: Operating ...

Find the combined key names in an object where the values can be accessed by index

I am currently working on creating a function called indexByProp, which will only allow the selection of props to index by if they are strings, numbers, or symbols. This particular issue is related to https://github.com/microsoft/TypeScript/issues/33521. ...

Remember to always call "done()" in Typescript + Mocha/Chai when dealing with async tests and hooks. Additionally, when returning a Promise, make sure it resolves correctly

It seems like I'm facing an old issue that I just can't seem to resolve, despite trying everything in my power. The error message reads: Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Pro ...

Discrepancy detected in AGM Map printout

When attempting to print my Angular AGM Map from Chrome, I noticed a large grey gap in the map. This gap is visible even when "background graphics" are turned off and it causes the map image below it to shift downwards. If you want to reproduce this issue ...

Creating a JSON schema for MongoDB using a TypeScript interface: a step-by-step guide

In order to enhance the quality of our data stored in MongoDB database, we have decided to implement JSON Schema validation. Since we are using typescript in our project and have interfaces for all our collections, I am seeking an efficient method to achie ...

Encountering a compilation error while trying to utilize a union type in a function parameter within an

As stated on https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html, it is recommended to utilize multiple types for a parameter in a function (refer to the union part) /* OK */ interface Moment { utcOffset(): number; ...

What are the benefits of sharing source files for TypeScript node modules?

Why do some TypeScript node modules, like those in the loopback-next/packages repository, include their source files along with the module? Is there a specific purpose for this practice or is it simply adding unnecessary bulk to the module's size? ...

The system is unable to locate a compatible object with the identifier '[object Object]' of type 'object'. NgFor is limited to binding with iterables like Arrays, not JSON data

Working with JSON data data:[ { assets:[[tool_order_id: "38",order_status_id: "10"]], order_info:[id: "1", order_type: "6",check: "1", current_Stage_id: "29"] }, { assets:[tool_order_ ...

What advantages could learning ReactJS first give me before diving into NextJS?

Just mastered TS and now faced with the decision of choosing a framework. I'm curious why it's recommended to learn ReactJS before NextJS. I've read countless articles advising this, but no one seems to delve into the reasons behind it. Ca ...

Encountering unspecified values when subscribing to a BehaviorSubject and receiving it as an Observable

My goal is to display the name of the currently logged-in user in the header of my application. However, I encountered an issue where upon refreshing the page, the value would be lost due to SPA behavior (even though the data is stored in local storage). T ...

There was an issue when attempting to create a unique component with the TAB feature in Angular Material

Looking to implement a custom TAB component using Angular Material 9. Here is the code snippet for creating a TAB with Angular Material: <mat-tab-group> <mat-tab label="First"> Content 1 </mat-tab> <mat-tab label=" ...

Retrieve content from my Tumblr API posts

Looking to retrieve my tumblr posts through an api. Successfully set up the api key using Angular2 and typescript. Utilizing jsonp to avoid any cross origin problems. Here is my current code snippet: var config = { params: { action: "query" ...