2
<?php 

 $value = json_decode(file_get_contents('php://input'));
 $mysql_pekare= new mysqli ("serv", "user","pass", "db");

 if(!empty($value)) {
 $stmt = $mysql_pekare->prepare("INSERT INTO users (`username`, `password`)  VALUES(?,?)"); 

 $stmt->bind_param("ss", $value->username, $value->password);
 $stmt->execute();

     if(!empty($stmt)) {

        $contacts = array(); 
        $id = mysqli_insert_id(); 
        $contact = array("objectId" =>  ($id));
        array_push($contacts, $contact);
        echo json_encode(array('results' => $contacts), JSON_PRETTY_PRINT);
     }

 $stmt->close();
 $mysql_pekare->close();

 }
 ?>

Now when I insert my info from my frontend the value (username + password) gets added into MySQL just fine with a unique ID but I do not get the returned ID, currently I get it like this:

   {
  "results": [
      {
  "objectId": null
      }
     ]
   }
medvedo
  • 543
  • 2
  • 8
  • 23
  • 4
    `$stmt->insert_id;` – splash58 Jun 24 '16 at 17:41
  • 2
    **Never store plain text passwords!** Please use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). Make sure you ***[don't escape passwords](http://stackoverflow.com/q/36628418/1011527)*** or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Jun 24 '16 at 17:43

3 Answers3

2

Your $id is most likely null or an error not sure...

//This is for procedural and needs a link
$id = mysqli_insert_id(); 
//should be
$id = mysqli_insert_id($mysql_pekare); 
//$mysql_pekare I am assuming is your connection...

//however you are using oo (or I think) so should be
$stmt->insert_id
nerdlyist
  • 2,842
  • 2
  • 20
  • 32
2

Based on an example in php.net this is what you want to change in your code

$id = $stmt->insert_id();
0

You forgot to add the database as parameter, mysqli_insert_id($link); But, anyway you mix up class style and procedural style.

Use $id = $mysql_pekare->insert_id;

lexx9999
  • 736
  • 3
  • 9