code: ‘ER_DUP_ENTRY’,
errno: 1062,
sqlMessage: “Duplicate entry ‘0’ for key ‘PRIMARY’”,
sqlState: ‘23000’,
index: 0,
sql: “INSERT INTO users SET name = ‘sukasuka123’, genre = ‘Rock’, instrument = ‘’, soundcloud = NULL, password = ‘1111’, role = ‘Band’, city = ‘Москва’, login = ‘<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>’”
}


const express = require(“express”);
const fs = require(“fs”);
const session = require(“express-session”);
const fileUpload = require(“express-fileupload”);
const app = express();
const fuzzball = require(“fuzzball”);
const mysql = require(‘mysql’);

const connection = mysql.createConnection({
host: ‘localhost’,
user: ‘music’, // замените на свой логин
password: ‘password’, // замените на свой пароль
database: ‘music’ // замените на свою базу данных
});

connection.connect((err) => {
if (err) {
console.error('Ошибка подключения к базе данных: ', err);
} else {
console.log(‘Подключение к базе данных успешно’);
}
});

app.set(“view engine”, “ejs”);
app.use(express.static(“public”));

app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: “mysecretkey”,
resave: false,
saveUninitialized: false
}));

const citiesAndRegions = JSON.parse(fs.readFileSync(“./db/russia.json”, “utf8”));


//const predefinedGenres = [‘Rock’, ‘Pop’, ‘Jazz’, ‘Hip Hop’, ‘Electronic’, ‘Blues’];

// Функция для получения последних музыкантов, зарегистрированных музыкантов
function getLastNRegisteredMusicians(N, callback) {
connection.query(“SELECT * FROM users ORDER BY id DESC LIMIT ?”, [N], (err, result) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}

function getMusicians(callback) {
connection.query(“SELECT * FROM users”, (err, result) => {
if (err) {
console.error("Ошибка при получении списка музыкантов: “, err);
return callback(err);
} else {
return callback(null, result);
}
});
}

// Функция для получения музыканта по id
function getMusicianById(id, callback) {
connection.query(“SELECT * FROM users WHERE id=?”, [id], (err, result) => {
if (err) {
console.error(“Ошибка при получении музыканта с id {id}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result[0]);
}
});
}

function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}

//search function
function search(term, role, city, genre, callback) {
const queryValues = [
`%{term.toLowerCase()}%,<br/> role === '' ? null : role,<br/> city === '' ? null : city.toLowerCase().trim(),<br/> genre === '' ? null : genre.toLowerCase()<br/> ];<br/><br/> const queryConditions = [<br/> 'name LIKE ? OR genre LIKE ?',<br/> 'role = ?',<br/> 'city = ?',<br/> 'genre = ?'<br/> ];//.filter(condition =&gt; queryValues[queryConditions.indexOf(condition)] !== null);<br/> queryConditions = queryConditions.filter(condition =&gt; queryValues[queryConditions.indexOf(condition)] !== null);<br/><br/> const sql = SELECT * FROM users WHERE {queryConditions.join(' AND ')}`;

connection.query(sql, queryValues, (err, result) => {
if (err) {
console.error('Ошибка при поиске: ', err);
callback(err, []);
} else {
const results = result.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/{musician.id},<br/> thumbnail: musician.thumbnail,<br/> soundcloud: musician.soundcloud,<br/> role: musician.role,<br/> city: musician.city<br/> };<br/>}).sort((a, b) =&gt; {<br/> const aNameScore = a.name.toLowerCase().startsWith(query) ? 2 : a.name.toLowerCase().includes(query) ? 1 : 0;<br/> const bNameScore = b.name.toLowerCase().startsWith(query) ? 2 : b.name.toLowerCase().includes(query) ? 1 : 0;<br/> const aGenreScore = a.genre.toLowerCase().startsWith(query) ? 2 : a.genre.toLowerCase().includes(query) ? 1 : 0;<br/> const bGenreScore = b.genre.toLowerCase().startsWith(query) ? 2 : b.genre.toLowerCase().includes(query) ? 1 : 0;<br/><br/> // Sort by name score, then genre score, then location score (descending)<br/> if (aNameScore + aGenreScore + a.city &lt; bNameScore + bGenreScore + b.city) {<br/> return 1;<br/> } else if (aNameScore + aGenreScore + a.city &gt; bNameScore + bGenreScore + b.city) {<br/> return -1;<br/> } else {<br/> return 0;<br/> }<br/> });<br/><br/> // Remove duplicates<br/> results = results.filter((result, index, self) =&gt;<br/> index === self.findIndex(r =&gt; (<br/> r.name === result.name && r.genre === result.genre && r.city === result.city<br/> ))<br/> );<br/><br/> callback(null, results);<br/> }<br/> });<br/>}<br/><br/>app.use((req, res, next) =&gt; {<br/> if (req.session.musicianId) {<br/> getMusicianById(req.session.musicianId, (err, musician) =&gt; {<br/> if (err) {<br/> console.error("Ошибка при получении current user: ", err);<br/> } else {<br/> res.locals.musician = musician;<br/> res.locals.userLoggedIn = true;<br/> res.locals.username = musician.name;<br/> }<br/> });<br/> } else {<br/> res.locals.userLoggedIn = false;<br/> }<br/> next();<br/>});<br/><br/>app.get("/", (req, res) =&gt; {<br/>getLastNRegisteredMusicians(5, (err, lastRegisteredMusicians) =&gt; {<br/>if (err) {<br/>console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);<br/>res.status(500).send("Ошибка получения данных");<br/>} else {<br/>res.render("index", { musicians: lastRegisteredMusicians, query:'',city:'',role:'',genre:'' });<br/>}<br/>});<br/>});<br/><br/>app.get("/autocomplete/cities", async (req, res) =&gt; {<br/>const searchString = req.query.term;<br/><br/>connection.query(<br/>"SELECT city FROM users WHERE city LIKE ?",<br/>[searchString + '%'],<br/>(error, results, fields) =&gt; {<br/>if (error) {<br/>console.error("Ошибка выполнения запроса: ", error);<br/>res.status(500).send("Ошибка выполнения запроса");<br/>} else {<br/>const cities = results.map(row =&gt; row.city);<br/>res.json(cities);<br/>}<br/>}<br/>);<br/>});<br/><br/>app.get("/register", (req, res) =&gt; {<br/> if (req.session.musicianId) {<br/> const musician = getMusicianById(req.session.musicianId);<br/> res.redirect("/profile/" + musician.id);<br/> } else {<br/> <br/> <br/> <br/> res.render("register", { citiesAndRegions, city:'', query:'',role:'' });<br/> }<br/>});<br/><br/>app.post("/register", (req, res) =&gt; {<br/> if (req.session.musicianId) {<br/> getMusicianById(req.session.musicianId, (err, musician) =&gt; {<br/> if (err) {<br/> console.error("Ошибка при получении музыканта: ", err);<br/> } else {<br/> res.redirect("/profile/" + musician.id);<br/> }<br/> });<br/> } else {<br/> const newMusician = {<br/> name: req.body.name,<br/> genre: req.body.genre,<br/> instrument: req.body.instrument,<br/> soundcloud: req.body.soundcloud,<br/> password: req.body.password,<br/> role: req.body.role,<br/> city: req.body.city,<br/> login: req.body.login,<br/> };<br/><br/> if (req.files && req.files.thumbnail) {<br/> const file = req.files.thumbnail;<br/> const filename = "musician_" + file.name;<br/> file.mv("./public/img/" + filename);<br/> newMusician.thumbnail = filename;<br/> }<br/><br/> connection.query("INSERT INTO users SET ?", newMusician, (err, result) =&gt; {<br/> if (err) {<br/> console.error("Ошибка при регистрации нового музыканта: ", err);<br/> res.status(500).send("Ошибка регистрации");<br/> } else {<br/> req.session.musicianId = result.insertId;<br/> res.redirect("/profile/" + result.insertId);<br/> }<br/> });<br/> }<br/>});<br/><br/>app.get("/profile/:id", (req, res) =&gt; {<br/>getMusicianById(parseInt(req.params.id), (err, musician) =&gt; {<br/>if (err) {<br/>console.error("Ошибка при получении музыканта: ", err);<br/>res.status(500).send("Ошибка при получении данных");<br/>} else {<br/>if (musician) {<br/>res.render("profile", { musician: musician, city:'', query:'', role:'' });<br/>} else {<br/>res.status(404).send("Musician not found");<br/>}<br/>}<br/>});<br/>});<br/><br/>app.get("/login", (req, res) =&gt; {<br/> res.render("login");<br/>});<br/><br/>app.post("/login", (req, res) =&gt; {<br/> connection.query("SELECT * FROM users WHERE login=? AND password=?", [req.body.login, req.body.password], (err, result) =&gt; {<br/> if (err) {<br/> console.error("Ошибка при входе: ", err);<br/> res.status(500).send("Ошибка при входе");<br/> } else {<br/> if (result.length &gt; 0) {<br/> req.session.musicianId = result[0].id;<br/> res.redirect("/profile/" + result[0].id);<br/> } else {<br/> res.render("login", { error: "Invalid login or password" });<br/> }<br/> }<br/> }<br/>);<br/>});<br/><br/>app.get("/logout", (req, res) =&gt; {<br/> req.session.destroy();<br/> res.redirect("/");<br/>});<br/><br/>app.get('/search', (req, res) =&gt; {<br/> const query = req.query.query || '';<br/> const role = req.query.role || '';<br/> const city = req.query.city || '';<br/> const genre = req.query.genre || '';<br/><br/> if (query || role || city || genre) {<br/> search(query, role, city, genre, (err, musicians) =&gt; {<br/> if (err) {<br/> res.status(500).send("Ошибка при выполнении поиска");<br/> } else {<br/> app.locals.JSON = JSON;<br/> res.render('search', { musicians, query, role, city, genre, citiesAndRegions});<br/> }<br/> });<br/> } else {<br/> // Use the getMusicians function instead of reading from musicians.json<br/> getMusicians((err, musiciansList) =&gt; {<br/> if (err) {<br/> res.status(500).send("Ошибка при получении списка музыкантов");<br/> } else {<br/> const musicians = musiciansList.map(musician =&gt; {<br/> return {<br/> name: musician.name,<br/> genre: musician.genre,<br/> originalName: musician.name,<br/> profileLink: /profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});

app.locals.JSON = JSON;
res.render(‘search’, { musicians, query, role, city, genre, citiesAndRegions});
}
});
}
});


app.get(”/profile/:id/edit”, requireLogin, (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error(“Ошибка при получении музыканта: “, err);
res.status(500).send(“Ошибка при получении данных”);
} else {
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render(“edit-profile”, { musician: musician });
} else {
res.status(403).send(“Access denied”);
}
} else {
res.status(404).send(“Musician not found”);
}
}
});
});





app.post(”/profile/:id/edit”, requireLogin, (req, res) => {
const musicianId = parseInt(req.params.id);
getMusicianById(musicianId, (err, musician) => {
if (err) {
console.error(“Ошибка при получении музыканта: “, err);
res.status(500).send(“Ошибка при получении данных”);
} else {
if (musician) {
const updatedMusician = {
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
soundcloud1: req.body.soundcloud1,
city: req.body.city,
role: req.body.role,
bio: req.body.bio,
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = “musician_” + musicianId + “_” + file.name;
file.mv(”./public/img/” + filename);
updatedMusician.thumbnail = filename;
}
connection.query(“UPDATE users SET ? WHERE id=?”, [updatedMusician, musicianId], (err, result) => {
if (err) {
console.error(“Ошибка при обновлении профиля музыканта: “, err);
res.status(500).send(“Ошибка при обновлении профиля”);
} else {
res.redirect(”/profile/” + musicianId);
}
});
} else {
res.status(404).send(“Musician not found”);
}
}
});
});

function isValidSoundCloudUrl(url) {
return url.startsWith(‘https://soundcloud.com/’);
}

app.listen(3000, () => {
console.log(“Server started on port 3000”);
});
ошибка при регистрации. насколько я понимаю, при регистрации, присваивается каждый раз id 0 для каждого нового юзера, который пытается зарегаться. проверь код