Insert multiple values sent from AJAX into sql database - php

hi have this code which works perfectly with just value:
<script type="text/javascript">
$(document).ready(function() {
$("input[type=button]").click(function () {
var textarea_content = $('textarea#wall').val(); // get the content of what user typed (in textarea)
if (textarea_content != '') { // if textarea is not empty
var sender = "<?php echo $_SESSION['user_id'];?>";
$.ajax({
type: "POST",
url: "send_message_function.php",
data : "action=send&from_id="+sender+"&to_user="+$(this).siblings("input[type=text]").val()+"&message="+textarea_content,
dataType: "json",
success: function (data) {
var LastID = data["cid"];
alert("toUser: " + $(this).siblings("input[type=text]").val()+"and text area " + textarea_content + " message id: " + LastID);
}
});//end success function
//do something else
} else {
alert('Enter some text ! '); // just in case somebody click on share witout writing anything :)
}
});//end click function
});//end ready function
</script>
and send_message_function.php :
<?php
require 'core/functions/init.php';
$action = $_POST['action'];
if($action=="send"){
$from_id = mysql_real_escape_string($_POST['from_id']);
$to_id = mysql_real_escape_string($_POST['to_user']);
$message = strip_tags($_POST['message']);
$sql = mysql_query("INSERT INTO chat (from_id, to_id, message, dt)VALUES('$from_id','$to_id','$message',NOW())") or die("0");
echo json_encode(array("cid"=>(mysql_insert_id()),
"from_id"=>''.$message_id.''));
}
?>
the problem is when I try to send the message to multiple users. The sql query try to insert all the users IDs in the same row. I know I should do some loop but I can't think how run the query for every users I want to send the message to.
$(this).siblings("input[type=text]").val()
returns multiple users id like this: 113,143,234

you do not need a loop, you can do multiple inserts with just one query, like this:
$to_id = explode(',', mysql_real_escape_string($_POST['to_user'])); //split the string to an array containing each id
$sql = mysql_query("INSERT INTO chat (from_id, to_id, message, dt) VALUES('$from_id','$to_id[0]','$message',NOW()), ('$from_id','$to_id[1]','$message',NOW()), ('$from_id','$to_id[2]','$message',NOW()) ") or die("0");
Note: $from_id shouldn't be a primary key, else you would get a duplicate key error.
Edit: If you do not know the no. of users,
$to_id = explode(',', mysql_real_escape_string($_POST['to_user']));
foreach ($to_id as $v)
$sql = mysql_query("INSERT INTO chat (from_id, to_id, message, dt) VALUES('$from_id','$v','$message',NOW()) ") or die("0");

You need to split the users ids string in the comma character, then execute a query for each value founded.

To insert multiple rows in one SQL query, do this
INSERT INTO foo(a, b) VALUES('c', 'd'), ('e', 'f'), ('h', 'i');
You'll need to loop to build each VALUES set, but you can do the insert in a single query.
So something like
<?php
$to_id = explode(',', mysql_real_escape_string($_POST['to_user']));
$sql = 'INSERT INTO chat (from_id, to_id, message) VALUES';
foreach ($to_id as $id)
{
$sql .="('$from_id', '$id', '$message'),";
}
rtrim($sql, ','); //strip the final comma
?>
That should form a query along the lines of
INSERT INTO chat(from_id, to_id, message) VALUES('1', '2', 'hello from php'), ('1', '3', 'hello from php'), ('1', '4', 'hello from php')
Doing it this way means only a single query is sent: therefore there's less overhead on communicating with the database which will speed up your script.

$toIDS = explode(',', mysql_real_escape_string($_POST['to_user']));
foreach($toIDS as $ID){
$query=mysql_query("INSERT INTO foo(a, b) VALUES('c', 'd')");
echo (mysql_affected_rows()>0)?$ID .'INSERTED':$ID.' NOT INSERTED';
}

Related

Inserting jQuery's Sortable list into MySql

I am trying to insert jquery's sortable list values into MySql. I have issues with looping in MySql while inserting.
I have sorted items like this
-------------
Sorted List
-------------
did-1
fid-1
fid-2
fid-3
After this I have used 'serialize' to get these sorted list
$('.sortable').sortable({
connectWith: '.sortable',
tolerance: 'pointer',
update: function (event, ui) {
$('#add_list').click(function(){
var data = $('#drop_list1').sortable('serialize');
$.ajax({
data: data,
type: 'POST',
url: 'addnewlist.php',
success: function(data){
}
});
});
}
What i want is - Multiple insertion for every 'did', a 'fid' should be inserted. In my MqSql - '(did-1 , fid-1)(did-1 , fid-2)(did-1 , fid-3)'
I have tried this in my PHP.
foreach($_POST['doc'] as $doc)
{
for($i=0;$i<count($_POST['doc']);$i++)
{
$form=$_POST[$i]['form'];
echo $sql="INSERT INTO addnewdoc(doc_id,form_id) VALUES ($doc,$form)";
$res=parent::_executeQuery($sql);
}
}
If I'm understanding this correctly you want to loop through the docs, and then loop through the forms for each doc. Will this work instead?
foreach($_POST['doc'] as $doc)
{
foreach($_POST['form'] as $form)
{
echo $sql="INSERT INTO addnewdoc(doc_id,form_id) VALUES ($doc,$form)";
$res=parent::_executeQuery($sql);
}
}
That ends up running an insert query for each combination. You would be better off building all of the values into a single query and then executing it one time. For example:
$sql = "INSERT INTO addnewdoc(doc_id,form_id) VALUES ";
$values = Array();
foreach($_POST['doc'] as $doc)
{
foreach($_POST['form'] as $form)
$values[] = "($doc,$form)";
}
$sql .= join(',', $values);
$res=parent::_executeQuery($sql);
That gathers all of the values into an array and then joins each of them into a string separated by commas. You can then run a single insert query to insert all of the values.

How to update mysql database fields in groups (using GROUP BY)

I have a table named youi in my database. All fields in the table already contain values except for the aff and desc fields. See image below.
Now, I have a form in my HTML page (See image below) where I want to update the desc and aff fields according to their camp. I have not yet dealt with this kind of setup before. I've been thinking how to do this for almost a day now but still can't seem to find a perfect solution. Could you give me ideas or solutions on how to achieve this? I'm using PHP and mySQL.
Thanks in advance!
The easiest way i see is using a different UPDATE for each of those lines.
You could do that in a loop in php where you construct your update with the values of aff, desc and campaign for each line.
The sql would be:
UPDATE tableName
SET aff = varAffiliate,
desc = varDescription
WHERE campaign = varCampaign;
The php part i'm not of much help, sorry.
You can use CASE, WHEN and THEN in a loop to make the one query.
This is a statement I created using a simple for loop to update a bunch of captions on a group of photos.
UPDATE Images SET caption = CASE imgID WHEN 389 THEN 'a' WHEN 390 THEN 'sdf' WHEN 391 THEN 'safasasadf' WHEN 392 THEN 'fs' WHEN 393 THEN 'dfdsf' WHEN 394 THEN 'sfdf' END WHERE imgID IN (389,390,391,392,393,394);
Hope that helps
aff = (case when somefield='slkd' then yyy end),
desc = (case when somefield='slkdfdsd' then xxx end)
I finally found a solution to this problem. I used combination of jQuery, AJAX, PHP and mySQL for it to work.
All <select> have the same id. The same for <input> and <label>. Here's a sample of my HTML code:
<select id="youiaff">
<option>1001</option>
<option>1007</option>
<option>1009</option>
<option>1013</option>
<option>1017</option>
<option>1018</option>
<option>1022</option>
</select>
<input id="youidesc" type="text" />
<label id="youicamp"></label>
<button type='button' class='btn btn-success saveyouiid'>Save</button>
What I did next was to create a jQuery code that will get all the values of <select>, <input> & <label> and put each of them in an array. I used their ids as identifiers. Here's the code:
var desc = $("input[id='youidesc']")
.map(function(){return $(this).val();}).get();
var aff = $("select[id='youiaff']")
.map(function(){return $(this).val();}).get();
var camp = $("label[id='youicamp']")
.map(function(){return $(this).text();}).get();
Then, I passed the variables to the PHP script using AJAX:
$.ajax({
type: 'post',
url: 'saveyouiid.php',
data: {
desc:desc,
aff:aff,
camp:camp,
},
success:function(data){
}
});
This codes will be executed upon clicking the save button. So the full jQuery/AJAX for this would be:
$('.saveyouiid').click(function(){
var desc = $("input[id='youidesc']")
.map(function(){return $(this).val();}).get();
var aff = $("select[id='youiaff']")
.map(function(){return $(this).val();}).get();
var camp = $("label[id='youicamp']")
.map(function(){return $(this).text();}).get();
$.ajax({
type: 'post',
url: 'saveyouiid.php',
data: {
desc:desc,
aff:aff,
camp:camp,
},
success:function(data){
}
});
});
The PHP script (saveyouiid.php) will then accept the values sent via AJAX. These values are arrays. What I did next was I combined the arrays to form a multidimensional array. Then, I get the individual values and perform the mySQL query. Here's what the script looks like:
<?php
$con = mysqli_connect("localhost","imu_fryu","frankyouiIMU2013","imu_frankyoui");
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$aff = $_POST['aff'];
$desc = $_POST['desc'];
$camp = $_POST['camp'];
$arr = array_map(null, $aff, $desc, $camp);
foreach($arr as $array)
{
$aff = $array[0];
if ($aff == ">> Select Affiliate ID <<"){
$affID = "0";
}else{
$affID = $aff;
}
$desc = $array[1];
$camp = $array[2];
$sql1 = "UPDATE youi SET aff = '$affID', descr = '$desc' WHERE camp = '$camp'";
if (!mysqli_query($con,$sql1)) {
die('Error: ' . mysqli_error($con));
}
}
mysqli_close($con);
?>
I hope this could help someone in the future. :)

How to return latest Mysql entry through JQuery/Ajax request

I am trying to pull the latest entry of a mysql table through ajax and display it as html content inside a div. I have ajax and php functioning correctly, the only problem I have is that I want to query for new entries and stack the results at a time interval within a loop and I've run into two problems: getting the data to behave like a normal javascript string, and getting the loop to only return unique entries.
update.php file
$con=mysqli_connect("mydbhost.com","username","password","database_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM conversations");
$j = 0;
while($row = mysqli_fetch_array($result))
{
$carray[j] = $row['comment'];
$j++;
}
$comment = (array_pop($carray));
echo $comment;
echo "<br>";
mysqli_close($con);
JQuery Ajax request loop:
$(document).ready(function(e){
var comment;
function commentLoop() {
comment = $('#testdiv').load('update.php');
$('#testdiv').append(comment);
setTimeout(commentLoop, 6000);
}
commentLoop();
$(document).focus();
});
The problem is by doing SELECT * FROM conversations you keep requesting whole table -- although you only take the last one.
Your code need to remember which comment has been loaded, and only get any comment newer than that.
For example, assuming your primary key is incremental, do SELECT * FROM conversations WHERE convid > ?. Replace ? with latest comment that has been loaded. If you're loading for the first time, just do SELECT * FROM conversations
You could pass the last comment id displayed using request parameter into update.php. Also I recomment returning the data in JSON format so you can return a collection of comment and id and parse it easily
This will count the comments in the table and select the last entered comment then pass them to ajax as json data only if the received count is lower than the count of the comments in the table:
PHP:
if(isset($_GET['data']))
{
$con = new mysqli('host', 'user', 'password', 'database');
$init_count = $_GET['data'];
$stmt1 = "SELECT COUNT(*) AS count FROM conversations";
$stmt2 = "SELECT comment FROM conversations ORDER BY date_column DESC LIMIT 1";
$total = $con->prepare($stmt1);
$total->execute();
$total->bind_result($count);
$total->fetch();
$total->close();
if( ($init_count != '') && ($init_count < $count) )
{
$lastComment = $con->prepare($stmt2);
$lastComment->execute();
$result = $lastComment->get_result();
$row = $result->fetch_assoc();
$lastComment->close();
$data = array(
'comment' => $row['comment'],
'count' => $count
);
}
elseif($init_count == '')
{
$data = array(
'comment' => '',
'count' => $count
);
}
$pdo->close();
echo json_encode($data);
}
HTML:
<input type="hidden" id="count" value="" />
JQUERY:
$(document).ready(function(e){
function getComment(){
var count = $('#test').val();
$.ajax({
type: 'get',
url: 'update.php?data=' + count,
dataType: 'json',
success: function(data)
{
$('#count').val(data.count);
if(data.comment) != $('#testdiv').html(data.comment);
}
});
}
getComment();
setInterval(getComment, 6000);
});
SELECT * FROM conversations order by insert_date desc limit 10
insert_date the date time comment is inserted, i hope you will have a field for storing that if not add it now

it is not inserting correct values in db?

I want to insert a sessionid and a set of students into the db.
The sessionid can be found in line of code below:
<td><input type='hidden' id='currentId' name='Idcurrent' readonly='readonly' value='4' /> </td>
A set of students are displayed in a select box as so:
<select id="studentadd" name="addtextarea">
<option value='1'>u08743 - Joe Cann</option>
<option value='4'>u03043 - Jill Sanderson</option>
<option value='7'>u08343 - Craig Moon</option>
</select>
Now I am using ajax to get both the sessionId value and the student's value and post them into a seperate php page where the insert happens by using code below:
function submitform() {
$.ajax({
type: "POST",
url: "updatestudentsession.php",
data: {
Idcurrent: $('#currentid').val(),
addtextarea:$('#studentadd').val()
},
dataType:'json', //get response as json
success: function(result){
if(result.errorflag){
$("#targetdiv").html('success');
}else{
//you got success message
$("#targetdiv").html('error');
$('#targetdiv').show();
}
}
});
}
Below is the seperate php file updatestudentsession.php where it is suppose to do the insert:
$studentid = array();
$studentid[] = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : '';
$sessionid = (isset($_POST['Idcurrent'])) ? $_POST['Idcurrent'] : '';
$insertsql = "
INSERT INTO Student_Session
(SessionId, StudentId)
VALUES
(?, ?)
";
if (!$insert = $mysqli->prepare($insertsql)) {
// Handle errors with prepare operation here
}
foreach($studentid as $id)
{
$insert->bind_param("ii", $sessionid, $id);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
}
$insert->close();
Now the problem I am having is that is not inserting the correct data in at all. It is insert the value 0 in both the SessionId and StudentId fields. Below is what the table should look like after the insert:
SessionId StudentId
4 1
4 4
4 7
Instead it looks like below:
SessionId StudentId
0 0
My question is what is causing it to not be able to retrieve and insert the correct data into the db?
Suppose part of problem is here:
Idcurrent: $('#currentid').val(),
In your HTML code ID is currentId when you are trying to get an element with id currentid. id selector is case sensitive. So, you simply pass nothing to your PHP as jquery can't find an element.
Not sure what is wrong with $studentid, but I see no reason to use an array there as you always pass only one value, so try to change your php code like below:
$studentid = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : array();
$sessionid = (isset($_POST['Idcurrent'])) ? $_POST['Idcurrent'] : '';
//var_dump($studentid);
//var_dump($sessionid);
//var_dump($_POST); - this is additionally to see whole $_POST variable.
$insertsql = "
INSERT INTO Student_Session
(SessionId, StudentId)
VALUES
(?, ?)
";
if (!$insert = $mysqli->prepare($insertsql)) {
// Handle errors with prepare operation here
}
foreach($studentid as $id)
{
$insert->bind_param("ii", $sessionid, $id);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
}
$insert->close();
Also, see at commented out var_dump lines at the beginning. They will print values of your variables so you will be able to see what is actually set there. (as it is ajax, you will need to open developer tools and see what is returned in result on network tab)
UPD:
According to the latest comment, appears that$_POST['addtextarea'] is an array. Because of that code is modified to handle that. Please note how that value is taken:
$studentid = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : array();
Old code, which is:
$studentid = array();
$studentid[] = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : '';
results in two level array. So $studentid is an array which contains one element which is an array also. That is why old for each loop is not working. $id were an array. And it was converted to 0
I think there is a probel in data :
data: {
Idcurrent: $('#currentid').val(),
addtextarea:$('#studentadd').val()
},
Try :
data: {
"Idcurrent": $('#currentid').val(),
"addtextarea":$('#studentadd').val()
},
Please not the double quotes "Idcurrent"

Any Changes to an Ajax script produces an Uncaught TypeError

I am going absolutely crazy here.. I have an ajax.php file that is used to autocomplete a list of names from a table called "contacts". The section of the script is below:
dispatch('/ajax/contacts/list', 'ajax_list_contacts');
function ajax_list_contacts() {
$user = new User(SessionManagement::get_logged_in());
$gid = $user->get_field('fKeyGroup');
$q_cons = mysql_query("SELECT '_id', CONCAT(first_name, ' ', last_name) AS `Name`
FROM `contacts`
LEFT JOIN `contact_type_options` ON contact_type_options._id = contacts.fKeyContactDetail
WHERE (
contacts.fKeyGroup = '{$gid}' AND contact_type_options.type = '2'
)")
or die(ErrorLog::handle(mysql_error()));
$out = array();
while (($row = mysql_fetch_assoc($q_cons)) != null) {
$out[] = $row;
}
echo json_encode($out);
}
The above script is called by:
$(function() {
$.ajax({
success: function(data) {
var names = [];
data = JSON.parse(data);
for (var i in data) {
names.push(data[i].Name);
}
$('[name=form-referral]').autocomplete(names);
},
url: '/ajax/contacts/list'
});
This works perfectly, and was originally to only call records that had a contact_type_option = 2. Now, I want to include all contact regardless of the contact type options.
I have tried to change the code entirely to just pull all contacts from the "contacts" table, I have tried removing the part of the script show below. I have tried to change the = '2' to != '3' (as there are only 1-3 different types, and I don't care if type 3 is included) I am mainly interested in types 1 and 2, but I will accept 1,2, and 3 if necessary ... but ANY change I make produces a Uncaught TypeError: Cannot read property '0' of null error. It does not make any sense to me why nothing I try is working.
AND contact_type_options.type = '2'
I have also tried the code below:
dispatch('/ajax/contacts/list', 'ajax_list_contacts');
function ajax_list_contacts() {
$user = new User(SessionManagement::get_logged_in());
$gid = $user->get_field('fKeyGroup');
$q_cons = mysql_query("SELECT `_id`, CONCAT(`first_name`, ' ', `last_name`) AS `Name`
FROM `contacts`
WHERE `fKeyGroup` = '{$gid}'")
or die(mysql_error());
$out = array();
while (($row = mysql_fetch_assoc($q_cons)) != null) {
$out[] = $row;
}
echo json_encode($out);
}
Please try just changing:
CONCAT(`first_name`, ' ', `last_name`)
to
CONCAT("first_name", ' ', "last_name")
Obviously that won't return the right data, but it will tell you if there are non-UTF8 characters in your data, which can cause issues with JSON encoding, as JSON only support UTF8 characters.
Obviously making sure your data is correct UTF8 in your database is the best practice, but if you need a quick fix you could just remove the non-UTF8 characters with What's this regex doing?

Categories