尝试达到我插入值后得到的返回ID,但mysqli_insert_id()返回null

时间:2016-06-24 17:36:37

标签: php mysql

def largest_digit(string_one):
    return max(int(ch) for ch in string_one.split() if ch.isdigit())

现在当我从我的前端插入我的信息时,值(用户名+密码)被添加到MySQL就好了,但是我没有得到返回的ID,目前我得到的是这样的:

<?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();

 }
 ?>

3 个答案:

答案 0 :(得分:3)

您的$ id很可能为null或错误不确定...

//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

答案 1 :(得分:2)

基于php.net中的example,这是您要在代码中更改的内容

$id = $stmt->insert_id();

答案 2 :(得分:0)

您忘记将数据库添加为参数mysqli_insert_id($ link);但是,无论如何,你混淆了阶级风格和程序风格。

使用$id = $mysql_pekare->insert_id;