const express = require('express');
const mysql = require('mysql');
const app = express();
const port = 3000;
app.use(express.static('public'));
app.set('view engine', 'ejs');
const dbConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root@123',
database: 'abc'
});
dbConnection.connect(err => {
if (err) {
console.error('Error connecting to MySQL:', err);
return;
}
console.log('Connected to MySQL');
});
app.get('/', (req, res) => {
res.render('search_result');
});
app.get('/search', (req, res) => {
const productName = req.query.name;
const query = 'SELECT * FROM product WHERE pname LIKE ?';
const searchPattern = `%${productName}%`;
dbConnection.query(query, [searchPattern], (error, results) => {
if (error) {
console.error('Error executing MySQL query:', error);
res.status(500).send('Error retrieving product data');
return;
}
res.send(results);
});
});
app.get('/store', (req, res) => {
const pimage = req.query.pimage;
const pname = req.query.pname;
const imageBuffer = Buffer.from(pimage, 'base64');
const insertQuery = 'INSERT INTO product (pimage, pname) VALUES (?, ?)';
const values = [imageBuffer, pname];
dbConnection.query(insertQuery, values, (error, results) => {
if (error) {
console.error('Error storing image and name in MySQL: ' + error.message);
res.status(500).send('Error storing image and name in MySQL');
return;
}
res.send('Image and name stored in MySQL table.');
});
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
/////////////////////////////////////////////// ejs file ///////////////////////////////
<!DOCTYPE html>
<html>
<head>
<title>Product Search</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$('#searchForm').submit(function (event) {
event.preventDefault();
var pkProductName = $('#productName').val();
$.get('/search', { name: pkProductName }, function (data) {
$('#results').empty();
if (data.length === 0) {
$('#results').text('No products found.');
} else {
data.forEach(function (product) {
var imageBase64 = btoa(String.fromCharCode.apply(null, product.pimage.data));
var imageSrc = 'data:image/png;base64,' + imageBase64;
$('#results').append('<div class="product">' +
'<h3>' + product.pname + '</h3>' +
'<img src="' + imageSrc + '" onclick="pkStoreImage(\'' + imageBase64 + '\', \'' + product.pname + '\')">' +
'</div>');
});
}
});
});
});
function pkStoreImage(pimage, pname) {
$.get('/store', { pimage: pimage, pname: pname }, function (data) {
console.log(data);
// Handle the response as needed
});
}
</script>
<style>
.product {
margin-bottom: 20px;
}
h3 {
margin-bottom: 5px;
}
img {
.jpg)
0 Comments