0

so I have a simple code here that will insert a data and will return the last inserted id. Here is my 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 INTO accounts (fname, age) VALUES (?, ?)");
  $data->execute(array($fname, $age));
  $newUserLastID = $conn->lastInsertId('accounts');
}

And what I wanted to do is to run the function and get the global variable like:

newUser('JohnDoe', '22');
$someVar = $newUserLastID; 

My problem is whenever I run this code, my CLI always crashes. Is there a way to fix this? I also get this on production server. I'm not getting any error besides this.

enter image description here enter image description here

(by just running the function, my CLI crashes)

wobsoriano
  • 12,348
  • 24
  • 92
  • 162

1 Answers1

1

Why not just return the new ID instead of using a global variable? So, the last line of your function would be:

return $newUserLastID

Then, when you call the function, you'd instead assign it to a variable, like this:

$myNewId = newUser('JohnDoe', '22');

I don't know if this is the cause of your error, but it might be a place to start.

fredrover
  • 2,997
  • 2
  • 17
  • 24