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

The argument type 'MouseEvent<HTMLButtonElement, MouseEvent>' cannot be assigned to the parameter type 'HTMLElementEvent<HTMLButton>'

Here is the code snippet that I am currently working on and encountering an error in the console: type HTMLElementEvent<T extends HTMLElement> = Event & { target: T; } toggleHandler = (e: HTMLElementEvent<HTMLButtonElement>) => ...

Troubleshooting Angular and ASP.NET Core MVC: Addressing the "Uncaught SyntaxError: Unexpected token '<'" issue with index file references post deployment

My application is built using ASP.NET Core MVC and an Angular UI framework. Everything runs smoothly in the IIS Express Development Environment, but when switching to the IIS Express Production environment or deploying to an IIS host, I encounter issues wi ...

Conceal or remove disabled years in Angular Material datepicker

I previously disabled years prior to 2018, but now I would like to hide or delete them. The year selection range currently starts from 1998, but it should begin at 2018 instead. Is there a way to display only 3-4 years instead of the current 24-year rang ...

Angular 10 - Timezone Detection and Interactive Calendar

I am encountering a major issue with the Angular DateTimePicker and TimeZone functionality. I need to dynamically switch the TimeZone at runtime in my component. Every date displayed on the frontend must be converted, while every date sent to the backend n ...

What could be causing the table to display empty when we are passing data to the usetable function?

Visit Codesandbox to view Table While the header appears correctly, I noticed something strange. When I console log the data props, it shows all the necessary data. However, when I try to console.log row, there doesn't seem to be any single object re ...

In Angular 2, when creating an assignment expression, the left-hand side must either be a variable or a property access

I am encountering an issue that states: The left-hand side of an assignment expression must be a variable or a property access. Whenever I use this block of code, it triggers the error mentioned above. Can someone assist me in resolving this? this.i ...

Exploring TypeScript integration with Google Adsense featuring a personalized user interface

After following a tutorial on implementing Google AdSense in my Angular App, I successfully integrated it. Here's what I did: In the index.html file: <!-- Global site tag (gtag.js) - Google Analytics --> <script> (function(i,s,o,g,r,a,m ...

Removing a row from a FormArray within a FormGroup is not the appropriate method for managing input fields within a MatTable

I am encountering an issue with my MatTable, which is formed from a formarray. When I delete a row, the values in the input fields of my table are not updating as expected. However, the data in the object reflects the correct changes after deleting the r ...

The element ion-virtual-scroll is unrecognized

<ion-virtual-scroll [items]="churchNewsList" approxItemHeight="120px"> <ion-item *virtualItem="let news"> {{ news }} </ion-item> </ion-virtual-scroll> I encountered an issue with the following error messag ...

Paper-dropdown-menu component failing to render properly in web browser

Encountering an issue with the rendered HTML for a basic paper-dropdown-menu. Instead of displaying as a styled menu, the list items are just appearing as a plain list on the page. Upon clicking the rendered paper-input component within the dropdown, the ...

angular clear transition state post animation

Recently, I've been working on this code snippet: animations: [ trigger('shake', [transition('* => *', /* some animation */)]) ] In addition to that, I have this piece of code: <app-button [@shake]="shake" > & ...

I'm experiencing an issue with my Next.js Airbnb-inspired platform where I am unable to save a listing to my favorites

While working on my Next.js Airbnb clone project, I encountered an issue with adding a Listing to favorites. The heart button component's color does not change when clicked, despite receiving a success response. Moreover, the addition to favorites is ...

Tips for incorporating JSON in server-side rendering using Angular Universal

Currently, I am in the process of developing an angular2-universal app for a university project which is also my bachelor thesis. My goal is to have this app rendered on the server using angular universal. However, I am facing a challenge in loading my .js ...

Change a nested for-loop into an Observable that has been transformed using RxJS

Currently, the following function is operational, but I consider it a temporary solution as I'm extracting .value from a BehaviorSubject instead of maintaining it as an observable. Existing Code Snippet get ActiveBikeFilters(): any { const upd ...

Angular 11 error: Unable to access 'scrollHeight' property of null object due to TypeError

I'm hoping that someone out there can assist me in solving this puzzling issue. I am trying to obtain the full scrollHeight of the page, but for some reason, I am only getting a third of it. setSize() { let DOMScrollable = this.elementRef.nativeEl ...

Firestore rules restrict access to the data, however the Angular project is still able to retrieve the collection - ERROR Error: Insufficient permissions or missing

I am currently working on an Angular project that is connected to a Firestore database. Within the database, there is a collection called users, and each document within this collection contains a nested collection named hugeCollection. I have updated the ...

Using Angular 2 to position a md-fab button with 'position: fixed' inside an inner component

Utilizing the md-fab-button from the initial angular2 material-framework has presented a challenge for me. I am attempting to set the md-fab-button(for adding a new entity) with position: fixed, but my goal is to position the button within an inner compone ...

Creating custom observables by utilizing ViewChildren event and void functions in Angular 12: A step-by-step guide

I am currently working on developing a typeahead feature that triggers a service call on keyup event as the user types in an input field. The challenge I face is that my input field is enclosed within an *ngIf block, which requires me to utilize ViewChildr ...

Disable the yellow curly error lines in Visual Studio Code

Currently, I am utilizing VSCode with ESlint for Typescript development. I'm curious about how to turn off or remove the yellow curled error lines in my code editor, like the ones displayed in this example image: https://i.stack.imgur.com/Zdtza.png M ...

What is the best way to ensure that my mat-slide-toggle only changes when a specific condition is met?

I'm having an issue with a function that toggles a mat-slide-toggle. I need to modify this function to only toggle when the result is false. Currently, it toggles every time, regardless of the result being true or false. I want it to not toggle when t ...