Difficultly running web socket based node.js web server on Heroku

I am trying to “deploy” my program that works with a web socket server. I am using Heroku but encountering the following error:

Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

I have spent several days stuck on this issue and keep going online to see recommendations about using Heroku but the changes dont seem to work. The code works locally if I use localhost instead of 0.0.0.0 and don’t use process.env.PORT. In that case too though, heroku open still gives an error.

Here’ a look at my code:

PROCFILE:

web: node server.js 

SERVER.JS

 const WebSocket = require("ws");

 const PORT = process.env.PORT || 3000;
 
 const server = new WebSocket.Server({port: PORT});

 server.on("listening", () => {
    console.log(`WebSocket server is listening on port ${PORT}`);
});

server.on("error", (error) => {
    console.error("WebSocket server encountered an error:", error);
});
 
 server.on("connection", ws => {
    console.log("Client connected!");

INDEX.HTML

const PORT = process.env.PORT || 3000;

    const ws = new WebSocket(`ws://0.0.0.0:${PORT}`)

    ws.addEventListener("open", () => {
      console.log("Connected!")

      ws.addEventListener("message", event => {
        const newData = JSON.parse(event.data)

The main recommendation I saw online was about Heroku’s dynamic ports and use of a global host but it doesnt seem to help. As an extra fyi, even if I change it to ws://localhost:${PORT} nothing happens.

Setting Wix H1 element text equal to JavaScript variable

new to Wix and JavaScript here. I want to set a H1 element to a JavaScript variable. I have encountered the problem that Wix doesn’t allow direct access to DOM, as stated in different Stack Overflow questions. I am specifically trying to do document.getElementById but that isn’t allowed, instead I have to use Wix’s own namespace. I am encountering the problem on this line: $w("#text").text = chosenwebsite;. Here is my full code:

// Velo API Reference: https://www.wix.com/velo/reference/api-overview/introduction
/* global document */

$w.onReady(function () {

    function getRandomInt(max) {
        return Math.floor(Math.random() * max);
    }

    const websites = ["Internet Archive", "number 2 ", "number 3"];
    const chosenwebsite = websites[(getRandomInt(3))];
    $w("#text").text = chosenwebsite;
    console.log(chosenwebsite);

});

And here is the code on the H1 element: <h1 id="text">websites</h1> (that’s it, nothing else). And yes, I have set the element id to “text” within the actual Wix editor. This is the error message I keep getting: “Property ‘text’ does not exist on type ‘HtmlComponent'”. I have tried swapping out “text” for “html” but that didn’t help

Thank you.

How can I update a part of an array and then write that specific updated information to a sheet in Apps Script?

First of all I have some experience with coding but it is mostly self taught and very rusty. I am trying to write a script that takes information about boxes and their contents from a spreadsheet with a check after date, and use that information to create calendar events for each box, and then write the event IDs back to the sheet in order to avoid creating duplicate events.

Piecing together various code and ideas from different posts I have managed to get the script to check if an event exists and if it doesn’t to create it. The issue I seem to be running into is I am trying to update the sheet with the newly created event IDs and I seem to only be able to grab the last event ID and write that single entry back. Here is what I have so far:

//    0 Box | 1 Location | 2 Date Closed | 3 Check Date | 4 Start Time | 5 Count | 6 EventID

function syncCal() {
  const calId = "correct calendar"; // Test calendar
  const cal = CalendarApp.getCalendarById(calId);
 
  const sh = SpreadsheetApp.openById("sheet link"); // Change to correct Spreadsheet
  const ss = sh.getSheetByName("Box Tracker"); // Change to correct sheet

  let data = ss.getRange(2,1,ss.getLastRow(),8).getValues();
  //let info = idRange.getValues();
  let box, loc, d1, d2, t, count, title;
  

  for (let i in data){
  box = data[i][0];
  loc = data[i][1];
  d1 = new Date(data[i][3]);
  t = new Date(data[i][4]);
  count = data[i][5];
  var id = [[data[i][6]]];
  title = "Check Box #" + box;
   
  d1.setHours(t.getHours(),t.getMinutes());
  d2 = new Date(d1.getTime() + 30 * 60000);

    // Check if event already exists, update it if it does
    // Excludes rows that have no value in A2:A
    
  if (box !== "") try {
    var event = cal.getEventSeriesById(data[i][6]);
    Logger.log("Verified " + event.getTitle() + ' ID: ' + event.getId());
    event.setTitle('got you'); // this is to "force error" 
    event.setTitle(title);
  } catch (e) {
    Logger.log("Creating event...")
    //cal.createEvent(title, new Date("March 3, 2010 08:00:00"), new Date("March 3, 2010 09:00:00"), {description:desc,location:loc});
    var newEvent = cal.createEvent(title, d1, d2, {description:count + " in box.",location:loc});
    data[i][6] = newEvent.getId(); // Update the data array with event ID
    
    var event = cal.getEventSeriesById(data[i][6]);
    Logger.log('Created new event ' + event.getTitle() + ' ID: ' + event.getId());
    
    event.setTitle(title);
    event.setDescription(count + " in box.");
    event.setLocation(loc);
    Logger.log(data[i][6]);
    }
  
    var eventID = id.concat([]);
    Logger.log('eventID Array');
    Logger.log(eventID);
  }


  var idRange = ss.getRange(2,7,eventID.length,1);

  // Record all event IDs to spreadsheet
  idRange.setValues(eventID);
  }

Here is an example spreadsheet that it is trying to use:
Snapshot of spreadsheet

I know I could just write all the values back to the sheet but I am trying to avoid doing that since that would overwrite the formulas that are present in the primary sheet.

Any and all help or advice would be greatly appreciated!

Search in DataTables does not work correctly

I switched from Bootstrap 3.0 to 4.6 and since then the search in a data table does not work correctly anymore.

I use the following scripts (+ the corresponding CSS files):

  • bootstrap.bundle.min.js (4.6.2)

  • dataTables.bootstrap4.js

  • jquery-3.6.0.min.js

  • jquery.dataTables.js (1.13.8)

  • jquery.dataTables.min.js (1.10.2)

I fill the following table with data from a database (it’s not the full code, just the important part):

<?php

$fieldlist = '<table id="fieldlist" class="display datatable table table-striped" data-cells="4">
<thead><td>Name</td> <td>Beschreibung wg. Analyse</td> <td>Pflicht?</td>    <td>Format / Bedingung / next / Ziel</td></thead><tbody>';

$fieldlist .= '<tr><td>     
<input class="form-control" type="text" name="fieldname_' . $i . '"     value="' . $field->feld . '"></td> ';
$fieldlist .= '<td> <span hidden>' . $field->feldname2 . '</span> 
<div class="row">
<div class="col-md-2"><input style="width:100%;" class="form-control" type="text"   name="feldnameNummer_' . $i . '"    value="' . $field->feldnameNummer . '" ></div>
<div class="col-md-6"><input class="form-control" type="text"   name="fieldname2_' . $i . '"        value="' . utf8_decode($field->feldname2 == 'undefined' ? "" : $field->feldname2) . '"></div> 
</div></td>';

$fieldlist .= '<td><input type="checkbox" name="pflicht_' . $i . '" id="pflicht_' . $field->feld . '" class="toggle" ' . $mandatory . '><label for="pflicht_' . $field->feld . '">&nbsp;  Pflicht</label></td>';

$fieldlist .= '<td><div class="row"><div class="col"><input class="form-control" type="text" name="typ_' . $i . '" id="typ_' . $i . '" disabled readonly value="' . $field->typ . '"></div>';

if ($field->typ == "textfield") {
    $fieldlist .= '<div class="col"><select class="form-control" name="format_' . $i . '"   style="width:100%;">' . $formatoptions . '</select></div></div>';
} elseif ($field->typ == "checkbox") {
    $fieldlist .= '<div class="col"><select class="form-control" name="format_' . $i . '">' .   $checkboxOptions . '</select></div>';
    $fieldlist .= '<div class="col"><select class="form-control" name="prop_' . $i . '">' . $checkboxType .     '</select></div></div>';
} elseif ($field->typ == "buttonfield") {
    $fieldlist .= '<div class="col"><select class="form-control" name="format_' . $i . '">' . $buttonType . '</select></div></div>';
}

$fieldlist .= '</td></tr>';
$i++;

$fieldlist .= '</tbody></table>';

The table looks good:

how the table looks like

If I now, for example, search for “BLZ” (from the 1st row – example row 1), then no result is displayed. The search function works for 2nd row and 4th row – example row 4, also not for 3rd row.

The following JavaScript will also be executed:

if ($(this).attr('data-cells') == '4' && $(this).attr('id') == 'fieldlist') {
    param = { "aoColumns": [null, null, null, null], "sPaginationType": "full_numbers", "bAutoWidth": false, "bProcessing": true};
} else if ($(this).attr('data-cells') == '4') {
    param = { "aaSorting": [[0, "desc"]], "aoColumns": [{ "sType": "date-eu" }, null, null, null], "sPaginationType": "full_numbers" };
}

Can’t Get Possible Moves for a Black Piece On a Chess board using chess.js [closed]

Am using chess.com library in my chrome extension project and I get to a point where I have to keep track of the possible moves that can be made by a piece from a particular position. I use the following approach for both the black and white pieces:

chess.put({type: type, color: 'w'}, to);
const possibleMoves = chess.moves({square: to});

I do the same for black pieces by specifying the color using ‘b’ and updating the other fields accordingly but this only works for scenarios like, from ‘d4’ e.t.c but not ‘c6’, ‘e6 and others.

Any help will be much appreciated.

How Can I Display Data From a CSV File in a Tabular Format in a Webpage Using Javascript?

I’ve created a ASP.Net Core Web API in C# using the .Net 8.0 Framework. It calls a command line utility, saves the output in a csv file, then formats that file as needed. I’ve already got a simple webpage where users can call the API, but I also want to read that csv file and display the contents to the webpage in a tabular format once the API is done running.

This is a sample from the csv file, and I want the data to look exactly like this on my webpage:
CSV File

My first “solution” to read the file and display the data onto my webpage was very manual, and not something I want to pursue. I made a file input type for users to select the csv file.

Here is the Javascript I used:

document.getElementById('inputFile').addEventListener('change', function(){
let fr = new FileReader();
fr.onload = function () {
    document.getElementById('output').textContent = fr.result;
}
fr.readAsText(this.files[0]);
})

And a sample of what was output to the webpage

Product Description Licenses Available  Licenses In Use UserID  Host    Start_Date
                    
NX Mach 3 Ind Design    39 licenses issued  3 licenses in use           
            ab012   TXABCCKLNWK8    Thu|2/22|23:30
            jsimmons    AG813341    Wed|2/28|5:12
            abr01   TXABC297Q9W2    Wed|2/28|7:16
                    
NX Mach 1 Design (Floating) 18 licenses issued  2 licenses in use           
            ab00001 TXABCCL18LQ6    Tue|2/27|0:22
            jjameson    AG815086    Wed|2/28|11:00

Does anyone have any ideas on how I can read in the csv file after the API is done running, and dynamically have the data fill in a table using Javascript?

Button “Details” not triggering the expected behavior in nested loop structure

I am facing an issue with the functionality of the “Details” button in my HTML code, and I am seeking assistance in identifying the problem.

I have a nested loop structure where I display information about countries, companies, and job vacancies.
Each country has a set of companies, and each company has a set of job vacancies.
The “Details” button is intended to reveal additional information about job vacancies when clicked.
When I click the “Details” button, nothing happens, and the job vacancies are not displayed as expected.
Here is my code

<div class="country-card" data-country="Угорщина">
        <img src="{{ asset('admin_assets/img/hungary.png') }}" alt="Угорщина Прапор">
        <span>Угорщина</span>
    </div>
    
    <div class="country-card" data-country="Словаччина">
        <img src="{{ asset('admin_assets/img/slovakia.png') }}" alt="Словаччина Прапор">
        <span>Словаччина</span>
    </div>
    
    <div class="country-card" data-country="Чехія">
        <img src="{{ asset('admin_assets/img/czech-republic.png') }}" alt="Чехія Прапор">
        <span>Чехія</span>
    </div>
    
    <br>
    <br>
    
    @foreach(['Угорщина', 'Словаччина', 'Чехія'] as $country)
    <!-- Блок країни -->
    <div class="country-block" id="{{ $country }}">
        <h2>{{ $country }}</h2>
        <div class="company-cards">
            @foreach($project->where('country', $country) as $rs)
                <!-- Картка компанії в обраній країні -->
                <div class="card company-card" style="" data-country="{{ $country }}" data-company="{{ $rs->company }}">
                    <div class="card-body">
                        <h5 class="card-title">{{ $rs->company }}</h5>
                        <p class="card-text">{{ $rs->city }}</p>

                        <!--Details button -->
                        <button class="btn btn-secondary details-btn">DETAILS</button> <br>
                    </div>
                </div>
                <br>

                @foreach($project->where('company', $rs->company) as $vacancy)
                    <!-- Картка вакансії для обраної компанії -->
                    <div class="card vacancy-card" style="margin: 10px;">
                        <div class="card-body">
                            <h5 class="card-title">{{ $vacancy->vacancy }}</h5>
                            <p class="card-text">{{ $vacancy->job }}</p> 
                            
                            <!-- Кнопка "Створити PDF" для вакансії -->
                            <button type="button" class="btn btn-primary details-btn" onclick="openPDFEditor('{{ $vacancy->id }}')">Створити PDF</button>

                            <!-- Модальне вікно редактора PDF для вакансії -->
                            <div id="pdfEditorModal_{{ $vacancy->id }}" style="display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: #fff; padding: 20px; border: 1px solid #ccc; box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); z-index: 9999; ">
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <h3>Редактор PDF</h3>
                                    <!-- Кнопка закриття модального вікна -->
                                    <button type="button" onclick="closePDFEditor('{{ $vacancy->id }}')">✖</button>
                                </div>
                                <hr>
                                <div style="display: flex;" >
                                    <div id="pdfPreview" style="margin-right: 20px; border: 1px solid #ccc;  "></div>
                                    <div>
                                        <!-- Форма для введення даних перед створенням PDF -->
                                        <label for="name">Країна</label>
                                        <input type="text" id="name" required>
                                        <br>
                                        <label for="email">Назва проектузаводу</label>
                                        <input type="email" id="email" required>
                                        <br>
                                        <!-- Кнопки для операцій з PDF -->
                                        <button type="button" onclick="generateAndPreviewPDF()">Створити і Переглянути PDF</button>
                                        <br> <br>
                                        <button type="button" onclick="downloadPDF()">Завантажити PDF</button>
                                    </div>
                                </div>
                            </div>
                        </div> 
                    </div> 
                @endforeach
            @endforeach
        </div>
    </div>
@endforeach

    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $('.country-block, .company-cards, .vacancy-card, .details-btn').hide();
    
            $('.country-card').on('click', function(){
                var countryId = $(this).data('country');
    
                $('.country-block').hide();
                $('#'+countryId).show();
    
                $('.company-cards').hide();
                $('#'+countryId+' .company-cards').show();
    
                $('.details-btn').show();
            });
    
            $(document).on('click', '.details-btn', function(){
                $('.vacancy-card').hide();
                $(this).closest('.company-card').find('.vacancy-card').show();
            }); 
        });

NS_BINDING_ABORTED when fetching image in JS

In a component, I simply have a <img /> which has a src attribute pointing to a file stored on my server (localhost:5000). In my node/express backend, I have the following code which makes the file public and accessible via url:

// Means http://localhost:5000/{filename} is publicly accessible. 
app.use("/", express.static(__dirname + "/public"))

When entering the URL above, I can successfully see files which are stored on my server.

However in my frontend React code, the image flickers . I have tried implementing onload to ensure the image has loaded as well as custom logic to only display the image if it has been loaded however this doesn’t fix the underlying problem of two requests being made. However, due to the issue still persisting, I inspected the network tab and discovered that two requests are being made to fetch the image. The first request is still a GET request, however is highlighted in red and displays NS_BINDING_ABORTED. What does this error mean, and why could it be occuring?. The subsequent request successfully fetches the image successfully.

I suspect this is the reason behind the issue with the image loading. I have researched solutions to the NS_BINDING_ABORTED and tried multiple solutions such as configuring cors, adding a type to button elements, as well as adding e.preventDefault() where neccessary, however still no solution.

This is the component which simply fetches the image from my server. It is eventually displayed and fetched, however only after the previous failed request (NS_BINDING_ABORTED)

import React from "react"
import { BASE_URL } from "../utils/config/config"
       
       const Test = () => {
           return (
               <div>
                   <img
                       width={100}
                       height={100}
                       src={"http://localhost:5000/breakingbad.jpg"}
                   />
               </div>
           )
       }
       
       export default Test

Also, this happens when trying to display images in other components, where the src of the image points to a file stored on my server running on port 5000. However the failed request does not occur when the src is set to a url somewhere on the web. It only seems to happen when pointing to files stored on my server, however Cross-Origin Resource Sharing is configured correctly on my server so I don’t think that’s the issue.

Any idea why two requests are being made when displaying the image, and also why the first request always fails with the code NS_BINDING_ABORTED? Thanks

How to tell TSC that some global names exist? [duplicate]

File tree

|-vendor
| |-lib.js
| |-lib.d.ts
|-index.html
|-main.ts

index.html

<body>
    <script src="vendor/lib.js"></script>
    <script src="generated/main.js"></script>
</body>

lib.d.ts

declare class GlobalName {
    static log(tag: string): void;
}

export = GlobalName;

lib.js

const GlobalName = {
    log: tag => console.log("GlobalName", tag),
};

GlobalName.log("javascript");

main.ts

GlobalName.log("typescript");

Then I run tsc main.ts --outDir generated. Open index.html and see both logs in the console, cool, it works.

The problem is, TSC thinks there are errors:

main.ts:1:1 - error TS2304: Cannot find name 'GlobalName'.

1 GlobalName.log("typescript");
  ~~~~~~~~~~

Which arguments can make TSC to assert that lib.d.ts will be accesible in main.ts?

Force initial-scale based on viewport width

is there a way to force the display-zoom / initial scale for a Vue-Webapp.

We want to do something like:

screen width <= 1460 px -> zoom100% / initial scale 1.0
screen width > 1460px -> zoom 110% / initial scale 1.1

Happy for any takes on this!:)

Tried it with basic js but didnt worked and we didnt find any resources on this topic.

Error: (0 , _context_UserContext__WEBPACK_IMPORTED_MODULE_3__.useUser) is not a function

I am trying to pass props from Dashboard to Header (Header in in the Layout), It works in dashboard, I can import it and get setUsers by destructuring assingment, but in Header, I cant do this for some reason
Layout.tsx:

import { UserProvider } from "@/context/UserContext";
import type { Metadata } from "next";
import { Montserrat } from "next/font/google";
import '../globals.css'
import Header from "./header/Header";
const monoton = Montserrat({subsets: ['latin']});

export const metadata: Metadata = {
  title: "Home",
  description: "Shared Drive project",
};


export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <UserProvider>
      <html lang="en" data-theme="light">
        <body className={monoton.className}>
          <Header />
          <main>
            {children}
          </main>
        </body>
      </html>
    </UserProvider>

  );
}

Dashboard.tsx:

'use client'
import React, { useEffect, useState } from 'react';
import { useUser } from '@/context/UserContext';

const Dashboard = () => {
  const { setUser } = useUser();
  useEffect(() => {
    const fetchUserData = async () => {
      console.log('dada')
      const response = await fetch('http://localhost:2525/api/user', { credentials: 'include' });
      if (response.ok) {
        const data = await response.json();
        setUser(data);
      }
    };
    fetchUserData();
  }, []);
  return (
    <div>
      Dashboard
    </div>
  );
};

export default Dashboard;

UserContext.tsx:

'use client'
import React, { createContext, useContext, useState, ReactNode } from 'react';

export type UserType = { 
  name: string; 
  id: string; 
  role: string; 
  email: string; 
  password: string;
};

export type UserContextType = {
  user: UserType | null;
  setUser: React.Dispatch<React.SetStateAction<UserType | null>>;
};

const UserContext = createContext<UserContextType>({
  user: null,
  setUser: (user) => {user= user},
});

export const useUser = () => useContext(UserContext);

export const UserProvider = ({ children }: { children: ReactNode }) => {
  const [user, setUser] = useState<UserType | null>(null);

  return (
    <UserContext.Provider value={{ user, setUser }}>
      {children}
    </UserContext.Provider>
  );
};
[enter image description here](https://i.stack.imgur.com/k2wFQ.png)

I dont understand why it keep saying this is not function

Using A JSX component in an Express Server | For React Email and Resend

So here’s what’s happening now.

I have a react frontend with react-email/components installed. I have created a component called Email.jsx and I’m trying to use this Component as the component for my E-mail. I know that the sending of email works because I have tested it with just plain html. There’s a react attribute in resend which would in theory allow me to use it. I have seen it work in videos, but I myself am running into issues. I will note that the frontend and express server are separate.

Here’s my email.jsx

import Logo from "../../public/images/logos/ecospring_logo_bordered.png";
import {
  Html,
  Button,
  Tailwind,
  Text,
  Section,
  Row,
  Column,
  Link,
  Img,
} from "@react-email/components";

const Email = (otp) => {
  return (
    <>
      <Html lang="en" dir="ltr">
        <Tailwind>
          <Section
            // align="center"
            // width="100%"
            // border="0"
            // cellPadding="0"
            // cellSpacing="0"
            // role="presentation"
            className="text-text-1 text-center max-w-[360px] bg-background-color border border-card-background rounded-md shadow-md mt-20 mx-auto py-68 px-0 md:px-4 font-roboto"
          >
            <Row className="w-full">
              <Column>
                <Img
                  alt="ecospring_logo.png"
                  height="88"
                  src={Logo}
                  className="p-4 mx-auto"
                  width="212"
                />
                <Text className="mt-16 font-semibold text-center  uppercase text-text-1">
                  Verify Your Identity
                </Text>
                <Heading
                  as="h1"
                  className="mt-4 text-2xl font-medium text-center text-text-1"
                >
                  Enter the following code to login.
                </Heading>
                <Section
                  // align="center"
                  // width="100%"
                  // border="0"
                  // cellPadding="0"
                  // cellSpacing="0"
                  // role="presentation"
                  className="bg-text-3 rounded-md mx-auto my-8 w-[280px]"
                >
                  <Section>
                    <Row>
                      <Column>
                        <Text className="py-8 text-3xl font-bold text-center">
                          {otp.map((code) => {
                            <Text className="inline-block px-3 py-2 border border-white text-text-1">
                              {code}
                            </Text>;
                          })}
                        </Text>
                      </Column>
                    </Row>
                  </Section>
                </Section>
                <Text className="mx-4 leading-relaxed text-center text-text-1">
                  Not expecting this email?
                </Text>
                <Text className="p-4 mx-4 leading-relaxed text-center text-text-1">
                  Contact{" "}
                  <Link href="mailto:[email protected]" className="underline">
                    [email protected]
                  </Link>{" "}
                  if you did not request this code.
                </Text>
              </Column>
            </Row>
          </Section>
        </Tailwind>
      </Html>
    </>
  );
};

export default Email;

server.js Express <- If I try to import it like below here, I get a cannot find module error

import Email from "../pos_frontend/src/mail/Email";

server.js <- Like this, I get TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".jsx"

import Email from "../pos_frontend/src/mail/Email.js";

I am sure that the path is correct, but I have no clue what I’m doing wrong.

server.js <- Resend Part

app.post("/otp", (req, res) => {
  try {
    const payload = req.body;

    resend.emails.send({
      from: "[email protected]",
      to: payload.email,
      subject: "EcoSprings OTP Code",
      html: `<p>PP Here IS OTP <strong>${payload.otp}</strong></p>`,
      // react: Email(payload.otp),
    });

    res.send("email sent succesfully ");
  } catch (error) {
    console.error("Error sending email:", error);
    res.status(500).send("Internal Server Error");
  }
});

Like I have mentioned earlier, it works fine without the React Component

Are get and set anti-pattern in “modern” Javascript? [closed]

Question(s):

  1. Are get and set anti-pattern in “modern” JavaScript?
  2. Does get foo (){... have any real benefits over getFoo(){...?
  3. Are there any style guides that have an opinion on their usage?

To my brain, get and set feel awkward. They hide the fact that they can be computed values and invoke a function call, which could be expensive or have side effects. Just now I spent 20 minutes trying to figure out how obj.foo changed even though I couldn’t find any assignments to obj.foo (it was a computed property based on other properties).

php file generating and reading data from a database

There is a function that generalize a php file:

require_once "connection.php";

// Módosítások elmentése vagy új termék hozzáadása
// Módosítások elmentése vagy új termék hozzáadása
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $new_name = isset($_POST["new_name"]) ? $_POST["new_name"] : "";
    $new_price = isset($_POST["new_price"]) ? $_POST["new_price"] : "";
    $new_image_url = isset($_POST["new_image_url"]) ? $_POST["new_image_url"] : "";

    if (isset($_POST["product_id"])) {
        /
        $product_id = $_POST["product_id"];
        updateProduct($product_id, $new_name, $new_price, $new_image_url);
    } else {
        
        $new_product_name = isset($_POST["new_product_name"]) ? $_POST["new_product_name"] : "";
        $new_price = isset($_POST["new_price"]) ? $_POST["new_price"] : "";
        $new_image_url = isset($_POST["new_image_url"]) ? $_POST["new_image_url"] : "";
        
        $new_product_id = generateSProductFile($new_product_name, $new_price, $new_image_url);
    }
}
function generateSProductFile($name, $price, $image_url) {
    global $conn;

   
    $insert_query = "INSERT INTO product (product_name, price, picture) VALUES (?, ?, ?)";
    $stmt = mysqli_prepare($conn, $insert_query);
    mysqli_stmt_bind_param($stmt, "sds", $name, $price, $image_url);
    mysqli_stmt_execute($stmt);

    /
    $new_product_id = mysqli_insert_id($conn);

    $file_path = "sproduct_" . $new_product_id . ".php";
    $file_content = "<?phpn";
    $file_content .= "$product_id = $new_product_id;n"; 
    $file_content .= "$product_name = "$name";n";
    $file_content .= "$product_price = "$price";n";
    $file_content .= "$product_picture = "$image_url";n";
    $file_content .= "?>n";
    $file_content .= file_get_contents("sproduct_template.php");
    
    
    file_put_contents($file_path, $file_content);

    return $new_product_id;
}

And there is the template file:


<?php
require_once "connection.php";




    
    $sql_product = "SELECT picture, product_name, price FROM product WHERE product_id = (SELECT MAX(product_id) FROM product)";
    $result_product = mysqli_query($conn, $sql_product);

    if ($result_product && mysqli_num_rows($result_product) > 0) {
        $row_product = mysqli_fetch_assoc($result_product);
        
        
        $product_name = $row_product['product_name'];
        $product_price = $row_product['price'];
        $product_picture = $row_product['picture'];
    } else {
        
        $product_name = "N/A"; 
        $product_price = "N/A";
        $product_picture = "default_image.jpg"; 
    
} else {
    
    $product_name = "N/A"; 
    $product_price = "N/A";
    $product_picture = "default_image.jpg"; 
}
?>

In addition, I also have a natural database, with the product table with manually entered products. The problem is that the newly generated php file shows incorrect product data. For some reason, it takes the data from the beginning of the database.
For example: I created a new product, and the database displayed the data of the product with ID 1 on the website.