Monzer Abdul Aziz
Monzer Abdul Aziz

Reputation: 45

mysql save image path without slashes nodejs

hello everyone I'm trying to save image path in mysql database but the database save the path without slashes like this

image: 'publicimagesIMG-1610544689539.jpg'

I copied it from the result but the query doesn't contain any problem!

INSERT INTO product (category,name,image,unit,price,stok,produce,end) VALUES ("Pastry" , "test" , "public\images\IMG-1610544689539.jpg" , "Kilo" , "80" , "100" , "2021-01-06","2021-01-15")

my code just save the values without edit anything in it

newProduct.post('/new' , upload.single('image') , async (req , res)=>{
  if(!req.file){
  res.redirect('/web')
  }
  const db = await newDB.connection()
  let query = `INSERT INTO product (category,name,image,unit,price,stok,produce,end) VALUES ("${req.body.category}" , "${req.body.name}" , "${req.file.path}" , "${req.body.unit}" , "${req.body.price}" , "${req.body.stok}" , "${req.body.produce}" , "${req.body.end}")`
  db.query(query)
  res.redirect('/web');
            
})

connection code ..

const pool = mysql.createPool(dbConfig);


const connection = () => {


  return new Promise((resolve, reject) => {

  pool.getConnection((err, connection) => {

    if (err) reject(err);
    console.log("MySQL pool connected: threadId " + connection.threadId);

    const query = (sql, binding) => {

      return new Promise((resolve, reject) => {

         connection.query(sql, binding, (err, result) => {

           if (err) reject(err);

           resolve(result);
           });
         });
       };

       const release = () => {

         return new Promise((resolve, reject) => {

           if (err) reject(err);
           console.log("MySQL pool released: threadId " + connection.threadId);
           resolve(connection.release());
         });

       };
       resolve({ query, release });
     });
   });
 };
const query = (sql, binding) => {

  return new Promise((resolve, reject) => {
    pool.query(sql, binding, (err, result, fields) => {
      if (err) reject(err);
      resolve(result);
    });
  });
};


module.exports = { pool, connection, query };

thank you

Upvotes: 0

Views: 316

Answers (1)

eliday
eliday

Reputation: 186

Instead of using a single slash, "" you could try using double slash "\". This can be achieved by doing the following before saving your path:

  let path = req.file.path
  path = path.replace("\", "\\")
    const db = await newDB.connection()
  let query = `INSERT INTO product (category,name,image,unit,price,stok,produce,end) VALUES ("${req.body.category}" , "${req.body.name}" , "${path}" , "${req.body.unit}" , "${req.body.price}" , "${req.body.stok}" , "${req.body.produce}" , "${req.body.end}")`

Upvotes: 1

Related Questions