我使用这段代码,并且它可以正常工作,参数值存储在数据库中,但我想在数据库中存储2个以上的值,我可以使用socket在数据库中传递多个值。 这是代码......
io.on('connection',function(socket){
console.log("A user is connected");
socket.on('status added',function(status){
add_status(status,function(res){
if(res){
io.emit('refresh feed',status);
} else {
io.emit('error');
}
});
});
});
var add_status = function (status,callback) {
pool.getConnection(function(err,connection){
if (err) {
callback(false);
return;
}
connection.query("INSERT INTO `status` (`s_text`) VALUES ('"+status+"')",function(err,rows){
connection.release();
if(!err) {
callback(true);
}
});
connection.on('error', function(err) {
callback(false);
return;
});
});
}
答案 0 :(得分:0)
我建议阅读文档: https://dev.mysql.com/doc/refman/5.7/en/insert.html
在你的情况下,它看起来像那样:
io.on('connection', function (socket) {
console.log("A user is connected");
socket.on('status', function (statusObject) {
add_status(statusObject, function (res) {
if (res) {
io.emit('refresh feed', statusObject.stat);
} else {
io.emit('error');
}
});
});
});
var add_status = function (statusObject, callback) {
pool.getConnection(function (err, connection) {
if (err) {
callback(false);
return;
}
connection.query("INSERT INTO `status` (`s_status`, `s_id`, `s_comment`) VALUES ('"
+ statusObject.stat + "', '" + statusObject.id + "', '" + statusObject.comment
+ "')", function (err, rows) {
connection.release();
if (!err) {
callback(true);
}
});
connection.on('error', function (err) {
callback(false);
return;
});
});
}
$(document).ready(function () {
var socket = io();
$("#add_status").click(function () {
socket.emit('status', {
stat: $("#status").val(),
id: $("#id").val(),
comment: $("#comment").val()
});
});
socket.on('refresh feed', function (msg) {
$("#show_comments").append(msg + '<br /><br />');
});
});