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.
Related
I need a PHP array that stores data from MySQL and later use in JQuery.
The sample data from MySQL table
student_id class_id score
001 01 A
001 02 B
002 02 A
In JQuery, I would like to access these data as data.student_id[i].class_id[i].score
How can I construct the PHP array?
My current codes in view_student.php (can choose more than one student_id, class_id)
$student_id = $_POST['student_id'];
$class_id= $_POST['class_id'];
$student_array = array();
for($j=0;$j<sizeof($student_id);$j++) {
$query = "SELECT class_id, score FROM student";
$query .= " WHERE student_id='".$student_id[$j]."'";
for($i=0;$i<sizeof($class_id);$i++){
if($i==0) {
$query .= " AND class_id=".$class_id[$i];
} else {
$query .= " OR class_id=".$class_id[$i];
}
}
if($student_sql=$connection->query($query)){
$student_php = array();
$student_row_php = array();
while($student_row_sql=$student_sql->fetch_array(MYSQLI_ASSOC)){
$student_row_php["student_id"]=$sale_row_sql['student_id'];
$student_row_php["score"]=$sale_row_sql['score'];
array_push($student_php, $student_row_php);
}
}
$student_array[$student_id[$j]]=$student_php;
}
echo json_encode($student_array);
In JavaScript, I need data.student_id[0].class_id[0].score instead of data.001[0].score
<script>
$(document).ready(function() {
$('form').submit(function(event) {
event.preventDefault(); /
var postForm = new FormData(this);
$.ajax({
type : 'POST',
url : 'view_student.php',
data : postForm,
processData: false,
contentType: false,
dataType : 'json',
success : function(data) {
$('#score').html('<font color="#FFFFFF"> <strong>'+data.001[0].score+'</strong> </font>');
}
});
});
});
Try to add this so that it resets the key indexing:
$student_array = array_values($student_array); // simple reindex
echo json_encode($student_array);
Since in the end they are already grouped by the students id, $student_id[$j] (contains 001, 002, etc), reset your keys so that you can access them thru your numeric indices, instead of using .001 which is the student id
This is my auto complete code. What should my PHP code look like in order
to receive the array that I put in the $.post() function?
var excludeArray = [];
$(".fb25").autocomplete({
source: 'vacation_get25Football.php',
focus: function(event, ui) {
$(this).val(ui.item.label);
return false;
},
select: function(event, ui) {
var exclude;
$(this).val(ui.item.label);
exclude = $(this).next().val(ui.item.value).val();
excludeArray.push(exclude);
// SENDING Exluded values to URL
$.post('vacation_get25Football.php', {'array[]': excludeArray});
// alert looks like (for example) 1,4,5
alert(excludeArray);
return false;
}
});
This is part of vacation_get25Football.php . My idea would be to insert certain values like, '1,3' into the IN() statement in sql. Doing this will subtract whatever values that are in IN() from the query. But For some reason I cannot get the array that I posted in Jquery to come up in PHP. From what I can tell, it's acting like $_POST['array']) isn't even being posted. Can any of you see what's wrong? Thank you.
if (($term = $_GET['term'])) {
if(($excludeArr = $_POST['array'])){
$test = 2;
}else{
/////////THIS IS THE ANSWER NO MATTER WHAT.
$test =1;
}
$objDB = mysqlDB();
$select_query = "SELECT team, ftball_id FROM tbl_football_top25
WHERE team
LIKE '%$term%'
AND NOT
ftball_id IN( $test )
;";
$prop_info = $objDB->getRecords($select_query);
$data = array();
if ($prop_info != "No records") {
FOREACH ($prop_info as $thisprop) {
array_push($data, array('label' => $thisprop['team'], 'value' => $thisprop['ftball_id']));
}
echo(json_encode($data));
}
//close db
$objDB->close();
}
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"
I'm trying to create a function where a user should select an option from a <select> and add a date to the value selected (inside <input type='text'> on the same row). Then when the fields have been inputted send as an array to a PHP file and inserted to a database.
I'm creating the <select>, and <input type='text'> dynamically on the same row in a table.
Selects look something like this: <input type='select' class='add_absence_type'>
Input fields: <input type='text' class='add_absence_date'>
The script I'm working on looks like this at the moment:
$('#save').click(function() {
function serealizeSelects (select)
{
var array = [];
select.each(function(){ array.push($(this).val()) });
return array;
}
function serealizeInputs (input)
{
var array = [];
input.each(function(){ array.push($(this).val()) });
return array;
}
var student_id = $('#student_id').val();
var add_absence_type = serealizeSelects($('.add_absence_type'));
var add_absence_date = serealizeInputs($('.add_absence_date'));
$.post('../updateAbsence.php', {
student_id: student_id,
add_absence_type: add_absence_type,
add_absence_date: add_absence_date
}, function(data) {
location.reload();
});
});
The $_POST data looks like this:
student_id 1
add_absence_date[] 2012-11-13
add_absence_date[] 2012-11-14
add_absence_type[] 1
add_absence_type[] 2
What do I need to do to create a PHP loop that creates mysql_query's like this? See below:
"INSERT INTO my_table (student_id, absence_type_id, absence_date) VALUES ('1', '1', '2012-11-13')"
"INSERT INTO my_table (student_id, absence_type_id, absence_date) VALUES ('1', '2', '2012-11-14')"
Try this way
<?php
$student_id = $_POST['student_id'] ;
$absence_date_arr = $_POST['add_absence_date'] ;
$absence_type = $_POST['add_absence_type'] ;
foreach($absence_date_arr as $key=> $absence_date){
mysql_query("INSERT INTO my_table (student_id, absence_type_id, absence_date) VALUES ('".$student_id."', '".$absence_type[$key]."', '".$absence_date."')");
}
?>
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';
}