Domanda

Utilizzo di questo codice PHP:

try{
    $dbh = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
    $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );  
    // INSERT CLEAN DATA INTO TABLE…
    $sth = $dbh->prepare("
    INSERT INTO Fan(fanNm,fanEmail,fanPass,fanDynamSalt)
    VALUES('$userName','$userEmailAddress','$userPassword','$dynamSalt')"
    );
    $sth->execute();
    ////////////////////////////////////////////////////////////////////
    ## Set Session Var for this PK ID in Fan table that is being created ##
    ////////////////////////////////////////////////////////////////////
    $_SESSION['newUserSessID'] = mysql_insert_id();
    echo "<strong style='color:#fff;'>".$_SESSION['newUserSessID']."</strong>";
} //try

catch(PDOException $e){
        echo "Oops, We're experiencing an error.";
        file_put_contents('/PDODBConnectionErrors.txt', $e->getMessage(), FILE_APPEND);  
} //catch
.

inserisce bene nel database, ma sto usando echo "<strong style='color:#fff;'>".$_SESSION['newUserSessID']."</strong>"; per echo out tale valore e restituisce sempre uno zero.

Anche se corro:

SELECT LAST_INSERT_ID( ) 
FROM Fan
LIMIT 0 , 30
.

Mi dà un'uscita come

0
0
.

(dal momento che ci sono due righe nella tabella del database)

Chiunque?

È stato utile?

Soluzione

Non è necessario utilizzare mysql_insert_id poiché non è parte di PDO (che è ciò che stai utilizzando per interagire con il database in questa istanza).

Utilizzare invece PDO::lastInsertId():

$_SESSION['newUserSessID'] = $dbh->lastInsertId();
.

Maggiori informazioni: http://www.php.net/manual/en/pdo.lastinsertid.php

Altri suggerimenti

Stai mescolando PDO con funzioni Generico MySQL.Il problema è il mysql_last_insert non ha risorse, e quindi restituisce 0 per false.Non mescolare PDO con funzioni Generico MySQL.

Per ottenere l'ultimo ID Inserisci in DOP, fai questo: $dbh->lastInsertId()

http://php.net/manual/en/pdo.lastinsertid.php

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top