0

I have the following code contain image upload and handling input text. I have to insert this values into the mysql database. I can't insert multiple values into the database. But I can even a single row values...

I can insert this response

{"name":"As","age":"12","imagePic":["userPic-1473665739434.jpeg"]}

I can't insert this response

{"name":["As","bs"],"age":["12","13"],"imagePic":["userPic-1473663782550.jpeg","userPic-1473663782628.jpeg"]}

var express = require('express');
var multer  =   require('multer');
var mime    =   require('mime');
var mysql = require('mysql');
var app = express();
var bodyParser =    require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  port      : 3306,
  password : '',
  database : 'test'
});

connection.connect(function(err){
if(!err) {
    console.log("Database is connected ... nn");    
} else {
    console.log("Error connecting database ... nn");    
}
});

var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now() + '.' + mime.extension(file.mimetype));
  }
});
var upload = multer({ storage : storage }).array('userPic');

app.get('/completeForm.html', function(req, res){
    res.sendFile(__dirname + '/' + 'completeForm.html')
});

app.post("/postFormAct", function (req, res, next) {
    upload(req,res,function(err) {
        /*console.log(req.body.user);
        console.log(req.body.email);
        console.log(req.files);*/
        var imgName = [];
        for(var i=0; i<req.files.length; i++) {
            imgName[i] = req.files[i].filename;
        }
        response = {
        name : req.body.user, 
        age : req.body.email, 
        imagePic : imgName
        };
        // res.send(JSON.stringify(response)); sample response eg: {"name":["As","bs"],"age":["12","13"],"imagePic":["userPic-1473663782550.jpeg","userPic-1473663782628.jpeg"]}
        if(!err) {

            connection.query('INSERT INTO nodetable SET ?',[response], function(err, result){
                if(!err) {
                res.send(response);
                }
                else{
                throw err;
                }
            });
        } 
        else {
            throw err;
        } 

    });

});

app.listen(3000);

Html code given below

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<form method="post" action="/postFormAct" enctype="multipart/form-data">
    <input type="text" name="user"><br>
    <input type="text" name="email"><br>
    <input type="file" name="userPic"><br>
    <div id="appendMore"></div>
    <input type="submit" value="Submit"><input type="button" value="Add More Fields" id="clickBtn">
</form>
<script>
    $(document).ready(function() {
    $("#clickBtn").click(function(){
        $("#appendMore").append('<input type="text" name="user"><br><input type="text" name="email"><br><input type="file" name="userPic"><br>');   
    });
    });
</script>

Database structure shown below

enter image description here

Please anybody help ...

ArK
  • 20,698
  • 67
  • 109
  • 136
Rijo
  • 2,963
  • 5
  • 35
  • 62
  • how to split {"name":["As","bs"],"age":["12","13"],"imagePic":["userPic-1473663782550.jpeg","userPic-1473663782628.jpeg"]} to this format ['As', '12', 'userPic-1473663782550.jpeg'], – Rijo Sep 12 '16 at 08:41
  • OK, I have posted a solution. See if this works for you. – A J Sep 12 '16 at 09:06
  • Try another answer. It should work for you. I'm deleting mine. – A J Sep 13 '16 at 01:30

1 Answers1

1

First of all for bulk MySQL insertion use this syntax (as also stated here How do I do a bulk insert in mySQL using node.js):

var myResponse = [
     ["As", "12", "userPic-1473663782550.jpeg" ],
     ["Bs", "13", "userPic-1473663782628.jpeg"]
];


connection.query('INSERT INTO nodetable (name, age, imagePic) VALUES ?',
                 [myResponse], function(err, result)
{
   if (!err) { res.send(myResponse); }
   else { throw err; }           
});

Hardcode it like that into the index.js - that should work as I tested it with your file and database structure right now.

For restructuring (proceed only if it worked hardcoded):

var original = {
    "name":["As","bs"],
    "age":["12","13"],
    "imagePic":["userPic-1473663782550.jpeg","userPic-1473663782628.jpeg"]
};

to

var myResponse =  [
    ["As", "12", "userPic-1473663782550.jpeg" ],
    ["Bs", "13", "userPic-1473663782628.jpeg"]
];

you can do:

var myResponse = [];
for (var i = 0; i < original.name.length; i++) {
    myResponse.push([
        original.name[i],
        original.age[i],
        original.imagePic[i]
    ]);
}
Michael Troger
  • 3,336
  • 2
  • 25
  • 41
  • Thanks Mr. Michael. Its working fine. I have doubt for without push operation we can't insert multiple response? is it possible reply ASAP – Rijo Sep 13 '16 at 03:44
  • I don't think you can insert the data into the database w/o restructuring it somehow. Of course you could also already on client side create the needed structure, but you would need to check everything on the backend anyway. If it solved your problem - could you please mark my answer as accepted? – Michael Troger Sep 13 '16 at 09:10
  • Not yet :) Please note here how to mark and upvote an answer: https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Michael Troger Sep 16 '16 at 08:20