0

I'm trying to insert data into one of my tables with AJAX.

This is my PHP Code:

include '../data/header.php'; //Here I get my DB-Connection Data from (username etc.)
$usernameToAdd = $_POST["usernameToAdd"];
$groupId = $_POST["groupId"];

$conn = new mysqli($dbserver, $dbuser, $dbpassword, $dbname);
$stmt = $conn->prepare("SELECT id FROM user WHERE username=?;");
$stmt->bind_param("s", $usernameToAdd);
$stmt->execute();
$stmt->bind_result($id);

if($stmt->fetch() > 0) {
    $stmtInsert = $conn->prepare("INSERT INTO group_membership (userId, groupId) VALUES (?, ?);");
    $stmtInsert->bind_param("ii", intval($id), intval($groupId));
    $stmtInsert->execute();
}

It's a group-relation table. A userId get's added to a groupId.

And here is the data that gets posted:

groupId 29
usernameToAdd user1

or as raw data

groupId=29&usernameToAdd=user1

I'm wondering where I made a mistake? The User "user1" definitely exists in the table user.

Also here is my JavaScript Code if you need that:

function addUserToGroup(btn){
    var groupId = btn.getAttribute("id").substring(13);
    var usernameToAdd = $("#addToGroup"+groupId).val();

    $.post("groups/addUserToGroup.php",
        {
            groupId: groupId,
            usernameToAdd: usernameToAdd
        },
        function (data, status) {
        });
}

It's always giving me a

Fatal error: Call to a member function bind_param() on boolean in D:\xampp\htdocs\myCalendar\groups\addUserToGroup.php on line 14

on this line $stmtInsert->bind_param("ii", intval($id), intval($groupId));

I don't know why and I've been trying to figure out for some time now.

Dileep Kumar
  • 1,053
  • 9
  • 14
Klausar
  • 125
  • 1
  • 8
  • Please check what type $stmtInsert has after you prepare the query and before you bind params. – BenRoob Jul 24 '17 at 07:33
  • 1
    Start with finding out what's the error: https://stackoverflow.com/questions/22662488/how-to-get-mysqli-error-in-different-environments – u_mulder Jul 24 '17 at 07:35
  • Unrelated error: You can't use `intval()` in `bind_param()`. The parameters have to be bound to variables, not functions. – Barmar Jul 24 '17 at 07:54

1 Answers1

0

you can try this way

$sql = "INSERT INTO group_membership (userId, groupId) VALUES (?, ?);";
if($query =  $conn->prepare($sql)){
    $stmtInsert ->bind_param("ii", intval($id), intval($groupId));
    $stmtInsert ->execute();
    //rest of code here
}else{
   //error !! don't go further
   var_dump($conn->error);
}

if any error so you will info about your error like table field name or datatype mismatch if not than work properly

Bhargav Chudasama
  • 6,348
  • 3
  • 19
  • 37