MySQL UUID primary key - generated by PHP or by MySQL?

六眼飞鱼酱① 提交于 2019-12-03 07:54:25
Colin O'Dell

No, it's not possible to have PHP generate the exact same UUID() as MySQL because it's a (completely) random number.

It sounds like your problem is that you like using UUID() in MySQL but don't want to execute an extra query to figure out what the new UUID is.

So why not have PHP create the UUID to be used as the primary key in your INSERT query?? This comment on php.net should show you how to do this.

Using those sample functions:

$uuid = UUID::v4();
$sql = "INSERT INTO mytable (uuid, foo) VALUES ('{$uuid}', 'bar');";
echo "The UUID is: ". $uuid;

Edit: There are several methods on that page which generate different types of UUIDs. v4 is pseudo-random, but you could use a different version or create your own UUID generator.

Amadeus

I tried the first step: $uuid = UUID::v4(); but it hung my server, so another idea came to mind which I tried as follows:

fetch data from query $sql1 = SELECT UUID() AS uuid ;
then store in variable $uuid

and then use below

$sql = "INSERT INTO mytable (uuid, foo) VALUES ('{$uuid}', 'bar');";
echo "The UUID is: ". $uuid;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!