php - Access lastInsertId variable outside a function -
so have simple code here insert data , return last inserted id
. here code:
function newuser($fname, $age) { global $newuserlastid; $conn = new pdo('mysql:host=localhost;dbname=mydb', 'root', ''); $conn->setattribute(pdo::attr_errmode, pdo::errmode_exception); $data = $conn->prepare("insert accounts (fname, age) values (?, ?)"); $data->execute(array($fname, $age)); $newuserlastid = $conn->lastinsertid('accounts'); }
and wanted run function , global variable like:
newuser('johndoe', '22'); $somevar = $newuserlastid;
my problem whenever run code, cli
crashes. there way fix this? on production server. i'm not getting error besides this.
(by running function, cli crashes)
why not return new id instead of using global variable? so, last line of function be:
return $newuserlastid
then, when call function, you'd instead assign variable, this:
$mynewid = newuser('johndoe', '22');
i don't know if cause of error, might place start.
Comments
Post a Comment