获取添加文件的ID

时间:2015-08-27 18:51:54

标签: php post mysqli

我有下表名为filescontent

ID  |  version  |  fileContent  | ownerID

我需要获取用户使用POST请求添加的文件的ID,然后我必须操纵它。我使用PHP和MySQLi。

2 个答案:

答案 0 :(得分:0)

mysqli_insert_id()应该可以解决问题。

小心确保在您想要id的插入查询和调用此函数之间没有放置其他查询,因为这会导致您获取错误文件的ID。

http://php.net/manual/en/mysqli.insert-id.php

答案 1 :(得分:0)

if($ _ POST){

$ name = mysqli_real_escape_string($ connection,$ _FILES ['uploadFile'] ['name']);

    $data = mysqli_real_escape_string($connection, file_get_contents($_FILES ['uploadFile']['tmp_name']));

    $select_version = mysqli_query($connection, "SELECT version FROM filescontent ORDER BY fileID DESC LIMIT 1");
    $fetch_version = mysqli_fetch_assoc($select_version);
    $increment_version = $fetch_version['version'] + 1;
    echo '<br>'.$increment_version .' версия';

    $select_fileID = mysqli_query($connection, "SELECT fileID FROM filescontent ORDER BY fileID DESC LIMIT 1");
    $fetch_fileID = mysqli_fetch_assoc($select_fileID);
    $increment_fileID = $fetch_fileID["fileID"] + 1;
    echo '<br>'. $increment_fileID.'ID';

    $selectName = mysqli_query($connection, "SELECT fileName FROM files WHERE fileName='$name'");
    $fetchName = mysqli_fetch_assoc($selectName);
    $fetchName = $fetchName['fileName'];

    $selectIDname= "SELECT fileID FROM files WHERE fileName = '$name'";
    $selectIDnameQuery = mysqli_query($connection, $selectIDname);
    $row = mysqli_fetch_array($selectIDnameQuery);
    $selectIDname = $row['fileID'];
    echo '<br><pre>'.print_r($row, true).'</pre>';

    $addedFileID = '';
    $selectAddedFile = "SELECT fileID FROM filescontent WHERE fileID='$addedFileID'";

    $a = mysqli_error($connection);
    echo '<br>'.$a.'<br>';  

    if(!strcmp($name, $fetchName)){
        echo 'The file exists';
        $query1 = mysqli_query($connection, "INSERT INTO filescontent (fileID, version, fileContent, author) VALUES ('$selectIDname', '$increment_version', '$data', 2)");
    }
    else{
        echo 'The file does not exist'; 
        $query2= mysqli_query($connection, "INSERT INTO filescontent (fileID, version, fileContent, author) VALUES ('$increment_fileID', 1, '$data', 2)");
        $query3 = mysqli_query($connection, "INSERT INTO files (fileID, fileName, ownerID) VALUES ('$increment_fileID', '$name', 2)");
    }

    $a = mysqli_error($connection);
    echo '<br>'.$a.'<br>';  
}