So i want to create a simple crud page using express and mysql2. When i request /:id and run query to search using WHERE, i get this warning even though i don't have that column.
"Unknown column 'favicon.ico' in 'where clause'
at PromiseConnection.execute"
My table
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| description | varchar(255) | YES | | NULL | |
| price | decimal(6,2) | YES | | NULL | |
+-------------+--------------+------+-----+---------+----------------+
My app.js
app.listen(3002, () => console.log(" Listening on Port 3002"));
app.use(express.urlencoded({ extended: true }));
app.set("view engine", "ejs");
app.engine("ejs", ejsMate);
app.use(cookieParser("keyboard cat"));
app.use(session({ cookie: { maxAge: 60000 } }));
app.use(flash());
app.get("/", async (req, res) => {
const connection = await mysql.createConnection({
host: "localhost",
user: "root",
database: "shop",
password: "password",
});
const [products] = await connection.execute("SELECT id,name FROM products");
connection.end();
console.log(req.session);
res.render("", { products, message: req.flash("success") });
});
app.get("/add", (req, res) => {
res.render("add");
});
app.get("/:id", async (req, res) => {
const { id } = req.params;
const connection = await mysql.createConnection({
host: "localhost",
user: "root",
database: "shop",
password: "password",
});
const [product] = await connection.execute(
`SELECT * FROM products WHERE id = ${id}`
);
connection.end();
res.render("product", { product });
});
Thanks before.
Looks like you do not have a favicon.ico
file in the directory where app.js
is sitting. Browsers will look for the "Favourite Icon" to display in the browser tab (and other places).
Let's look at this line:
app.get("/:id", async (req, res) => {
The :id
is taking anything that comes from the path. So, if the URL is http://localhost/app.js
, then the browser is going to ask for http://localhost/favicon.ico
. :id
will take favicon.ico
as the value.
Then we come down to this section of code:
const [product] = await connection.execute(
`SELECT * FROM products WHERE id = ${id}`
);
There you go. This is why you get Unknown column 'favicon.ico' in 'where clause'
. The SQL Query is literally:
SELECT * FROM products WHERE id = favicon.ico
This is dangerous. Do not release this to production.
The code is wide-open to SQL injections.
Be sure to add some validation to :id
and to use prepared statements when querying the database. This will reduce — but not eliminate — the risk of a script-kiddy from ruining your day.