Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vanys's avatar
Level 1

undefined binding when compiling UPDATE using knex

it's show this error :

Error: Undefined binding(s) detected when compiling UPDATE. Undefined column(s): [id] query: update "products" set "name" = ?, "price" = ?, "stock" = ?, "description" = ? where "id" = ?

here is my products.repository.js for update :

const updateProduct = async (newProduct) => {
  const{
    id,
    name,
    price,
    stock,
    description
  }= newProduct

  try {
    const product = await knex("products").where('id',id).update({
      'name':name,
      'price':price,
      'stock':stock,
      'description':description
    });
    return product;
  } catch (error) {
    console.log(error);
    console.error(error)
    throw new Error("Failed to update the product");
  }
};

my products.service.js for update

const updateProduct = async (req) => {
  try {
    const newProduct = new Product(req)
    return await productRepository.updateProduct(newProduct);
  } catch (error) {
    throw error;
  }
};

my product.route.js for update

router.put("/api/products", productController.updateProduct);

and last, my products.controller.js for update

const updateProduct = async (req, res) => {
    try {
      const product = await productService.updateProduct(req.body);
      res.status(201).json({ message: "product data updated succesfully"});
    } catch (err) {
      res.status(500).json({ message: "update product failed" });
    }
  };
0 likes
1 reply
vincent15000's avatar

I don't know knex.

But it looks like you are creating a new product (that means with a null id) to update it (which has no sense to try to update a new product).

To update a product, you should retrieve an existing product.

In your code, I don't see any place where you initialize the id from the retrieved product.

const updateProduct = async (newProduct) => {
  const{
    id, // new product, so a null id
    name,
    price,
    stock,
    description
  }= newProduct

  try {
    const product = await knex("products").where('id',id).update({ // so here the id is null
      'name':name,
      'price':price,
      'stock':stock,
      'description':description
    });
    return product;
  } catch (error) {
    console.log(error);
    console.error(error)
    throw new Error("Failed to update the product");
  }
};

Please or to participate in this conversation.