0

I am trying to get the UUID that had just been inserted.

This works in phpMyAdmin. But throws an error in PHP.

$insert = $conn->query(" 

    SET @usr_uuid = uuidToBin(UUID());

    INSERT INTO `users` (`users`.`usr_uuid`) VALUES ( @usr_uuid );

    SELECT HEX(@usr_uuid) AS usr_uuid;
");

However I get this error:

[errno] => 1064
[sqlstate] => 42000
[error] => You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT INTO `users` (`users`.`usr_uuid`) VALUES ( @u' at line 3

How do I go about fixing this?

Nikk
  • 7,384
  • 8
  • 44
  • 90

1 Answers1

-1

You have two options to do it.

The first of all, are using transactions. For example:

$conn->begin_transaction();
$insert = $conn->query("SET @usr_uuid = uuidToBin(UUID());";
$insert = $conn->query("INSERT INTO `users` (`users`.`usr_uuid`) VALUES ( @usr_uuid );";
$insert = $conn->query("SELECT HEX(@usr_uuid) AS usr_uuid;";
$conn->commit();

This option only works if you're using mysqli and innodb storage engine.

Second option, doing two queries:

$insert = $conn->query("INSERT INTO `users` (`users`.`usr_uuid`) VALUES ( uuidToBin(UUID() );";
$insert = $conn->query("SELECT HEX(usr_uuid) AS usr_uuid FROM `users`;";

This option can fall in the problem of having a new insert while you're doing it. But, if the table users have an ID, you can use mysql-insert-id() as suggested by @user3783243

Sakura Kinomoto
  • 1,784
  • 2
  • 21
  • 30
  • You don't need transactions; variables persist for the session. Your second method will return *all* the records - not just the inserted one. – symcbean Dec 12 '18 at 12:30
  • I don't know the table. It's because this, on second option I've suggested the user of mysql-insert-id(), but without an EXPLAIN TABLE I cannot know if there's an AUTO_INCREMENT column to use it. – Sakura Kinomoto Dec 12 '18 at 12:47