返回插入行的id(自动增量)

时间:2014-11-25 19:25:07

标签: php mysql

  1. 我将数据插入名为' roster'的表格中。第一列(id_roster)是使用mysql自动增量的id。
  2. 我运行SELECT来查找id_roster
  3. 我使用此id_roster将其插入表格&rus_par_membre'以及其他数据

    if ($insert_stmt = $mysqli->prepare("INSERT INTO `roster`(`nom_roster`, `description_roster`, `id_organisation`, `created_by`, `creation_date`,`modified_by`) VALUES (?, ?, ?, ?, ?, ?)")) {
    
        $insert_stmt->bind_param('ssiisi', $roster_name, $description_roster, $organisation_id, $user_id, $creation_date, $user_id);
    
        if (!$insert_stmt->execute()) {
                $reponse = 'Sorry, a database error occurred; please try later';
            } else {
                // if INSERT OK -> create a new line in roster_membre table
                    //1. get the roster_id
                    $sql = "SELECT r.id_roster 
                                FROM roster r
                                WHERE r.nom_roster = ?
                                LIMIT 1";
                    $stmt = $mysqli->prepare($sql);
    
                        if ($stmt) {
                            $stmt->bind_param('s', $roster_name); 
                            $stmt->execute();    // Execute the prepared query.
                            $stmt->store_result();
                            $stmt->bind_result($id_roster);
                            $stmt->fetch(); 
    
                            $level = 1;
                        //2. create a line with the roster_id and insert the membre as level 1 
                            $insert_stmt = $mysqli->prepare("INSERT INTO `roster_par_membre`(`id_membre`, `id_roster`, `level`, `modified_by`) VALUES (?,?,?,?)");
                            $insert_stmt->bind_param('iiii', $user_id, $id_roster, $level, $user_id);
                            $insert_stmt->execute();
    
                        $reponse = 'success';
                        }   
    
  4. 到目前为止,代码工作正常,但不是很好。 有没有办法在表中创建一个新行来直接返回一个值(带有自动增量的id)以在sql查询中使用(将数据插入到第二个表中)?或者可能将两个查询(两个INSERT)合并在一个语句中?

    简短编辑:它是AJAX $响应的返回值(JSON)

2 个答案:

答案 0 :(得分:0)

好,溶液:

                //1. get the roster_id
            $sql = "SELECT r.id_roster 
                        FROM roster r
                        WHERE r.nom_roster = ?
                        LIMIT 1";
            $stmt = $mysqli->prepare($sql);

                if ($stmt) {
                    $stmt->bind_param('s', $roster_name); 
                    $stmt->execute();    // Execute the prepared query.
                    $stmt->store_result();
                    $stmt->bind_result($id_roster);
                    $stmt->fetch(); 

只需要用

替换所有这部分
$id_roster =  $mysqli->insert_id;
好又轻松。感谢albanx

答案 1 :(得分:0)

这些是我用于查询项目的函数,我不想使用任何框架(只是php):

/**
     * 
     * Executes query methods
     * @param string $query the query string
     * @param array $vals array of values
     * @param bool $show show the query
     * @return int/array/false
     */
    function q($query, $vals=array(), $show_query=false) 
    {
        $conn = new mysqli(...)
        $offset = 0;
        foreach ($vals as $v) 
        {
            $cv     = $conn->real_escape_string($v);//escape the value for avoiding sql injection
            $fv     = ($v===NULL) ? 'NULL':"'".$cv."'"; //if value is null then insert NULL in db
            $qpos   = strpos($query, '?', $offset);//replace the ? with the valeue
            $query  = substr($query, 0, $qpos).$fv.substr($query, $qpos+1);
            $offset = $qpos+strlen($cv)+1;
        }

        $result = $conn->query($query);

        if($show || $result===false) echo $query."<br>";
        $rows = array();
        if($result===true)
        {
            return $conn->affected_rows;
        }
        else if($result===false)
        {
            return false;
        }
        else 
        {
            while ($row = $result->fetch_array(MYSQLI_ASSOC) ) 
            {
                $rows[]=$row;
            }
        }

        return $rows;
    }

    function lastid()
    {
        return $this->qval("SELECT LAST_INSERT_ID()");
    }

用法示例:

q('INSERT INTO USER(name, email) VALUES(?,?)', array('admin','admin@admin.com'));
$id = lastid();