Refresh current data without removing any fields in MySQL

Below is the snippet of my code:

app.put("/update/:id", (req, res) => {
    const userID = req.params.id;
    const sql = "UPDATE quotes SET `first_name` = ?, `last_name` = ?, `company` = ?, `email` = ?, `phone` = ? WHERE id = ?"
    const values = [my values]
    db.query(sql, [...values, userID], (err, data) => {
        if (err) return res.send(err)
        return res.json(data)
    })
})

I am encountering the following error message:

{
    "code": "ER_BAD_NULL_ERROR",
    "errno": 1048,
    "sqlState": "23000",
    "sqlMessage": "Column 'first_name' cannot be null",
    "sql": "UPDATE quotes SET `first_name` = NULL, `last_name` = NULL, `company` = NULL, `email` = NULL, `phone` = NULL WHERE id = '2'"
}

I aim to update only the first_name field without affecting other fields and their existing records.

Answer №1

To determine which values are set in your data, you can utilize the following syntax:

UPDATE quotes SET 
  `first_name` = COALESCE(?, first_name),
  `last_name` = COALESCE(?, last_name), 
  `company` = COALESCE(?, company), 
  `email` = COALESCE(?, email), 
  `phone` = COALESCE(?, phone) 
WHERE id = ?

The COALESCE() function returns the first non-NULL argument. By using this structure, if any parameter is NULL, each column will revert to its previous value as a default.

Answer №2

attempt:

app.put("/update/:id", (req, res) => {
    const uniqueID = req.params.id;
    const { first_name, last_name, company, email, phone } = req.body; // Check that req.body holds the latest information

    const sqlQuery = `
        UPDATE entries 
        SET 
            first_name = COALESCE(?, first_name),
            last_name = COALESCE(?, last_name),
            company = COALESCE(?, company),
            email = COALESCE(?, email),
            phone = COALESCE(?, phone)
        WHERE id = ?`;

    const dataValues = [first_name, last_name, company, email, phone, uniqueID];

    db.query(sqlQuery, dataValues, (err, results) => {
        if (err) return res.send(err);
        return res.json(results);
    });
});

Every field will be modified with a new value or retain its current value if no fresh input is given, hence ensuring records are updated without removing any fields

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

Utilizing MYSQL triggers for maintaining identical data across two tables

In order to maintain identical data in two tables for a temporary period while transitioning to a new system, I am facing the challenge of dealing with the inadequate MySQL structure of the old system. Without wanting to alter configurations of either the ...

Is it possible to save an HTML5 Canvas screenshot directly onto the page?

After browsing numerous tutorials on saving HTML5 canvas screenshots as images and opening them in new tabs, I'm wondering if there's a way to display the captured screenshot in a pre-set div on the SAME WEBPAGE. Any suggestions or solutions woul ...

Are you utilizing content loaded through jquery load in your work?

I have successfully utilized jQuery's .load() function to retrieve the contents of a table from another webpage and insert it into the current page, which is functioning properly. However, when I try to run scripts afterwards that manipulate the newly ...

transferring data from a dataset to an Oracle table function using SQL

Currently, I have developed a function that accepts a CLOB parameter and returns a table of strings. This allows me to easily retrieve results utilizing the function in a SELECT statement. create or replace TYPE t_process_teilenummer_tab AS TABLE OF VARCHA ...

"Twice the loading of Meteor templates: once with an undefined collection, and once with it

After searching various resources for solutions to my issue, I stumbled upon this helpful and . Both of these links provided valuable insights. The issue I'm facing is that one of my templates is loading twice - first with the collection undefined, ...

Divide the array object based on the "@" symbol

i am in possession of the following array object let old_array = { "valone": "facebook", "notification": "new message! @[email protected] @[email protected]" } i aim to extract all users with @ sign into a new array like displayed below le ...

Struggling to differentiate between Node.js and Angular

After a lot of reading and attempts to integrate NodeJS & Angular, I'm still struggling to make it work. I have set up the server.js, mainController, and index.html. The server is running fine but Angular seems to be giving me trouble. It has been one ...

Issue with retrieving data using Mysql Query

Search Query: SELECT t1.id, t1.ads_city, t1.ads_title, t1.ads_description, t1.ads_type, t2.ads_activate, t2.postads_id, t2.ads_id FROM table_1 t1 JOIN nextpostads t2 ON t1.id = t2.postads_id WHERE MA ...

What is the implication when Typescript indicates that there is no overlap between the types 'a' and 'b'?

let choice = Math.random() < 0.5 ? "a" : "b"; if (choice !== "a") { // ... } else if (choice === "b") { This situation will always be false because the values 'a' and 'b' are completely disti ...

Transferring data from one HTML element to another using Angular [Ionic]

My project involves utilizing an ionic slide box to display a series of images within it. <ion-slide-box> <!-- I am looping through the images based on the image count --> <ion-slide ng-repeat="n in [].constructor(imageCount) track by $in ...

Troubleshooting the issue of Concurrency in Java Spring: @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.SERIALIZABLE) failing to

Working on a Java (Spring/Hibernate) project where I am creating a timed and quantity-limited sale platform. My goal is to sell only 1000 cards of a certain type within the time slot of 10am-11am. However, I face a challenge as I receive approximately 150, ...

Is it possible to update the state before initiating an API call that relies on that specific state in React?

useEffect(() => { resetState(); if (page === 'ADMISSION') { fetchAdmissionKitPosts(); } else if (page === 'WEEKLY') { fetchWeeklyKitPosts(); } else if (page === 'FESTIVAL') { fetchFestivalK ...

A step-by-step guide on creating a unique ticket number sequence in PHP

Looking to create a unique ticket number sequence using PHP? Here's the given sequence: 1-W1 (mandatory). 2-Date (yy-dd-mm) format. 3-001-999 (resets daily from 001). Check out this example: e.g. - W120200101001 I've started the code below, b ...

Unforeseen outcomes of JavaScript when using the let and var keywords

In JavaScript, when using the var keyword to declare a variable, the JS engine assigns a default value of "undefined" at creation stage. console.log(message); // undefined var message = "My message"; However, with the let keyword: console.log(message); ...

Firefox compatibility issue caused by jQuery's appendTo function disrupting hyperlink functionality

I've successfully implemented the material design ripple effect using jQuery, which functions well in IE11 and Chrome 46. However, I've encountered an issue in Firefox 39 where applying the effect to links prevents redirection. Upon investigation ...

Implementing hashing with resumable.js

Looking for a way to include hashing in resumable.JS by utilizing the "fileAdded" event hook. Any suggestions on how to add hash to each chunk? ...

Is it possible to make a link_to, which is essentially a normal <a href>, clickable through a div that is also clickable?

I am currently dealing with a clickable div element which has a collapse functionality, and there is also a link placed on top of it: <div class="panel-group" id="accordion"> <div class="panel panel-default"> <div class="panel-h ...

SQL Query-employee Identification

I need help with a SQL query for updating employee IDs in a table. The employee IDs can have a length of 5, 6, or 8 digits, but my parent reports employee IDs as 8 digits long. If an employee ID is 5 digits, I want to add '100', if it's 6 d ...

Issue with Bootstrap Modal failing to display the dialog box

I have been attempting to incorporate a Bootstrap Modal for quite some time now. Despite following the guidelines in the bootstrap documentation, I am still unable to get it to work properly. Any ideas why this jsfiddle link is not functioning as expected? ...

Incorporate a collection of multiple images into Fancybox

Can someone help me figure out how to use fancybox to display a series of images in a lightbox? I have this JS object called fancybox_img, and here's what it contains: {card_173: Array(1), card_171: Array(5), card_169: Array(4)} card_169: Array(4) 0: ...