3

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?

user1914374
  • 1,220
  • 2
  • 11
  • 21

2 Answers2

2

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

Viktor S.
  • 12,736
  • 1
  • 27
  • 52
  • var_dump($_POST) showing this: `array(1) { ["addtextarea"]=> array(1) { [0]=> string(2) "4" } }`. This is when I trying to only insert student 4 into db. It is inserting 0 for SessionId and 1 for StudentId which strange – user1914374 Jan 11 '13 at 10:28
  • Hm. Ok. You have no session id passed at all. Suppose that is because of wrong selector. try to change `Idcurrent: $('#currentid').val(),` to `Idcurrent: $('#currentId').val(),`. Suppose session will be fixed that way. About studentId - strange why it is an array, but anyway. Let me update my answer to show how it should work. – Viktor S. Jan 11 '13 at 10:32
  • @user1930247 see my updated answer. UPD section describes changes. Code is also changed! – Viktor S. Jan 11 '13 at 10:37
  • Before you update I just wanted to show var dump if multiple students were being inserted `array(1) { ["addtextarea"]=> array(3) { [0]=> string(2) "39" [1]=> string(2) "40" [2]=> string(2) "36" } }` I will test your update – user1914374 Jan 11 '13 at 10:47
  • Only issue now is that it is not selecting the SessionId from the $sessionid variable. The number is being display when I change input from hidden to text. Could it be because button and Id are in seperate forms? I will display an update underneath question. Give me 5 mins – user1914374 Jan 11 '13 at 11:09
  • In your JS code, have you changed `Idcurrent: $('#currentid').val(), ` to `Idcurrent: $('#currentId').val(),`? – Viktor S. Jan 11 '13 at 11:16
  • Best answer and upvote, thanks, can I ask a little free question if you don't mind, I included an update showing full php code, is the select statement in the correct place to check to see if the data has been inserted? Should variable in bind param be $id or $studentid? I will delete the update after your comment. Its just that I am pretty much finish and just wanted to make sure – user1914374 Jan 11 '13 at 11:25
  • Variable in bind param should be $id. You should run it in for loop, just like when you do an insert. Place is ok. But I do not think you need it at all. You are checking errno after query execution, so if something goes wrong - you will know about that. Additionally: see [here](http://stackoverflow.com/q/2871866/1558311). And doing a select - well, you can do that and place is correct. But still, I do not think you need it there at all. – Viktor S. Jan 11 '13 at 11:38
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"

Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
  • 2
    This won't make a difference. Valid identifiers are allowed as keys in ECMAScript Object Literals and are implicitly converted to strings. Consider `({foo: "bar"})["foo"]` which is valid syntax and evaluates to `"bar"`. –  Jan 11 '13 at 08:59